多个动态创建的输入字段值不能超过指定数量

Multiple dynamically created input field values cannot exceed a specified number

我有多个拖放区(上传元素),其中为添加的每个文件显示预览元素。每个预览都有一个输入数字字段。

每个 dropzone 都是一个表单,其中包含一个隐藏的输入字段,其中包含一个值,该值是 dropzone 元素内所有输入字段的允许总和。

例如:

Dropzone 1 has total sum of: 10
And two previews with inputs, then for example this is possible:
input1: 10
input2: 0
Or 
input1: 5
input2:5
etc

只要总数是10。您不应该超过 10 或者当例如 input1 的值是 3 时,第二个输入不应该超过 7

我尝试了以下方法:

const attributeVal = $input;

attributeVal.on("change paste keyup input", function(e) {
  let newVal = Math.floor($input.val());
  newVal = Math.max(0, newVal);
  newVal = Math.min(10, newVal);
  const maxValue = parseInt(aantal);
  let valueSpent = 0;
  $input.not(this).each(function() {
    valueSpent += +$input.val();
  });
  if (newVal + valueSpent > maxValue) {
    // Invalid, reset these points to the maximum allowable:
    newVal = maxValue - valueSpent;
  }
  // New value has been validated, put it into the DOM:
  $input.val(newVal);
});

attributeVal.on("cut copy paste", function(e) {
  e.preventDefault();
});

其中 $input 是当前预览中的输入字段,aantal 是总和。问题是(在本例中 aantal = 10)每个输入字段都可以有 10(不超过)所以它看不到其他输入的值。

我尝试将 $input.not(this).each(function() { 更改为 $input.each(function() {,但是当我添加两张图片并因此有两个输入字段时,我只能在每个输入字段中转到 5。总数是 10,所以这是正确的,但不可能在一个中添加 9,在另一个中添加 1,每个最多只能添加 5

我怎样才能得到那个结果?

我在这里添加了一个 jsfiddle:https://jsfiddle.net/ar2395bw/(要获得预览,您可以将文件拖到大框中或单击它们并上传一些文件)。

JSFiddle 中的代码存在一些问题(上面发布的代码不足以诊断问题)。

没有找到所有 $input

let $preview = $(file.previewElement);
let $input = $preview.find('.fileinput');

您的 $preview 与每个文件相关联,因此您只会找到一个 $input,即正在更改的那个。

错误使用.each()

$input.not(this).each(function() {

传递给 .each() 的函数必须接受索引和值作为参数。按照目前的设置,$input 将在循环的每次迭代中始终引用相同的值。

尝试使用 sanitised / modified value

计算总数
  newVal = Math.max(0, newVal);
  newVal = Math.min(10, newVal);

这里确保newVal在0-10范围内,然后你使用changed值来计算总newVal + valueSpent > maxValue

解决方案

以下代码修复了所有这些问题。

const attributeVal = $input;

attributeVal.on("change paste keyup input", function (e) {
  const maxValue = parseInt(aantal);
  let valueSpent = 0;
  $preview.closest('.dropzone').find('.fileinput').each(function (index, input) {
    valueSpent += +$(input).val();
  });
  if (valueSpent > maxValue) {
    // Invalid, reset these points to the maximum allowable:
    $input.val($input.val() - (valueSpent - maxValue));
  }
});

attributeVal.on("cut copy paste", function (e) {
  e.preventDefault();
});

这在 JSFiddle 上对我有用。

存在多个问题:

  1. 并非每个拖放区都有 aantalinput
  2. aantalinput 必须是 class 而不是 id let aantal = $el.find('.aantalinput').val();
  3. $input 从当前拖放区一直到 let $input = $('table').find('.fileinput');
  4. let $input = $('table').find('.fileinput'); 必须在 attributeVal.on("change paste keyup input", function(e) {const attributeVal =$preview.find('.fileinput');

let counter = 0;
$('.dropzone').each(function(index, element){
    let $el = $(element);
    let $maxfiles = $el.attr('maxfiles');
    let $inputquantity = $el.find('input').val();
    let uploaded_preview = $('.hiddendiv').html();
    let aantal = $el.find('.aantalinput').val();
    let $thisdropzone = $el;
    
    let total_container = $el.parent().find('.row-total');
    
    $el.dropzone({
        paramName: 'postedFile',
        addRemoveLinks: true,
        dictDefaultMessage: '<i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span>',
        dictRemoveFile: 'Verwijder',
        dictCancelUpload: 'Annuleren',
        dictInvalidFileType: 'Dit type bestand is niet toegestaan',
        dictCancelUploadConfirmation: 'Weet je zeker dat je het uploaden wilt annuleren?',
        dictMaxFilesExceeded: 'Maximale aantal bestanden overschreden',
        maxFiles: $maxfiles,
        acceptedFiles: '.jpg, .jpeg, .png, .pdf, .tif, .tiff',
        thumbnailWidth: '205',
        thumbnailHeight: '140',
        thumbnailMethod: 'crop',
        previewTemplate: uploaded_preview,
        processing: function (file) {

        },
        // File contains dropzone file object, response contains ajax response from php file
        error: function (file, response) {
            
            counter++;
            console.log('Option ' + counter);
            response = '[{"status":"error","filename":"instablok'+counter+'.jpg","filesize":22822,"tmp_name":"\/tmp\/phpI6ov6y","height":172,"width":565,"heightcm":"6'+counter+',07","widthcm":"19'+counter+',93","tifwidth":null,"dpi":"72"}]';

let file_meta = JSON.parse(response);
  let $preview = $(file.previewElement);
  let $plusbtn = $preview.find('#plusupload');
  let $minbtn = $preview.find('#minupload');
 
    
    const attributeVal =$preview.find('.fileinput');

 attributeVal.on("change paste keyup input", function(e) {
       let $input = $('table').find('.fileinput');
      let newVal = Math.floor(this.value);
      newVal = Math.max(0, newVal);
      newVal = Math.min(10, newVal);
      const maxValue = parseInt(aantal);
      let valueSpent = 0;
     $input.not(this).each(function() {
        valueSpent += parseInt(this.value);
      });
      if (newVal + valueSpent > maxValue) {
        // Invalid, reset these points to the maximum allowable:
        newVal = maxValue - valueSpent;
      }
      // New value has been validated, put it into the DOM:
      this.value = newVal;
    });

    attributeVal.on("cut copy paste", function(e) {
      e.preventDefault();
    });
            

            if(file_meta[0].status == 'success'){

            }else if(file_meta[0].status == 'error'){
                $preview.find('.vrijgevenbtn').show();
                $preview.find('.foutformaat').show();
            }
            $preview.find('.bestandnaam').text('Bestandsnaam: ' + file_meta[0].filename);
            $preview.find('.resolutie').text('Resolutie: ' + file_meta[0].dpi + ' DPI');
            $preview.find('.formaat').text('Formaat: ' + file_meta[0].heightcm + ' x ' + file_meta[0].widthcm + 'cm');
        },
    })
});
.hiddendiv {
   display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
<script type="text/javascript">
  // Disable auto discover for all elements:
  Dropzone.autoDiscover = false;

</script>
<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css">

<table class="table upload-table">
  <tbody>
    <tr>
      <td class="plantmore-product-thumbnail uploadimg" width="100">
        <a href=""><img src="assets/images/noimg.jpg" alt=""></a>
      </td>
      <td class="plantmore-product-name" width="200">
        <div class="prodinfocheckout">
          <a class="prodname" href="">
            Monomeer
          </a>
          <span id="togglespecscheckout" class="prodspecscheckout noselect">
            <i class="fas fa-chevron-down"></i> Specificaties
          </span>
          <div class="togglespecscheckout">
            Hoogte : 20cm
            <br>
            Breedte : 20cm
            <br>
            uploaden : 1
            <br>
            Lijmlaag : Wit
            <br>
            Laminaat : Anti-slip laminaat
            <br>
            Afwerking : Contoursnijden
            <br>
          </div>
        </div>
      </td>
      <td class="plantmore-product-quantity" width="190">
        <span class="centervertical">
          <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
          </button>
          <span class="amount">
            Benodigd formaat:<br>
            <span class="benodigd">20 x 20cm</span>
          </span>
        </span>
      </td>
      <td class="plantmore-product-quantity" width="185">
        <span class="centervertical">
          <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
          </button>
          <span class="amount">Benodigde aantal<br> bestanden: <span class="benodigd">10</span></span>
        </span>
      </td>
      <td class="plantmore-product-quantity">
        <span class="centervertical">
          <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
          </button>
          <span class="amount">Bestanden <br>toegewezen: <span class="benodigd">0 / 10</span></span>
        </span>
      </td>
      <td class="plantmore-product-quantity" valign="top">
        <button class="uploadbutton btn yellowbtn dz-clickable">Bestand(en) uploaden</button>
      </td>
    </tr>
    <tr class="newrow">
      <td colspan="6">
      <h6 class="row-total">total: 0     </h6>
        <form action="upload/uploaden.php" class="dropzone dropzoneform dz-clickable" maxfiles="10" id="dropzone1">
          <input type="hidden" value="Monomeer" name="productnaam">
          <input type="hidden" value="Twan" name="klantnaam">
          <input type="hidden" value="20" name="hoogte">
          <input type="hidden" value="20" name="breedte">
          <input class="aantalinput" type="hidden" value="10" name="aantal">
          <div class="dz-default dz-message"><span><i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span></span></div>
        </form>
      </td>
    </tr>
    <tr>
      <td class="plantmore-product-thumbnail uploadimg" width="100">
        <a href=""><img src="assets/images/noimg.jpg" alt=""></a>
      </td>
      <td class="plantmore-product-name" width="200">
        <div class="prodinfocheckout">
          <a class="prodname" href="">
            Monomeer
          </a>
          <span id="togglespecscheckout" class="prodspecscheckout noselect">
            <i class="fas fa-chevron-down"></i> Specificaties
          </span>
          <div class="togglespecscheckout">
            Hoogte : 90cm
            <br>
            Breedte : 90cm
            <br>
            uploaden : 1
            <br>
            Lijmlaag : Wit
            <br>
            Laminaat : Anti-slip laminaat
            <br>
            Afwerking : Contoursnijden
            <br>
          </div>
        </div>
      </td>
      <td class="plantmore-product-quantity" width="190">
        <span class="centervertical">
          <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
          </button>
          <span class="amount">
            Benodigd formaat:<br>
            <span class="benodigd">90 x 90cm</span>
          </span>
        </span>
      </td>
      <td class="plantmore-product-quantity" width="185">
        <span class="centervertical">
          <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
          </button>
          <span class="amount">Benodigde aantal<br> bestanden: <span class="benodigd">1</span></span>
        </span>
      </td>
      <td class="plantmore-product-quantity">
        <span class="centervertical">
          <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
            <i class="fas fa-info-circle"></i>
          </button>
          <span class="amount">Bestanden <br>toegewezen: <span class="benodigd">0 / 1</span></span>
        </span>
      </td>
      <td class="plantmore-product-quantity" valign="top">
        <button class="uploadbutton btn yellowbtn dz-clickable">Bestand(en) uploaden</button>
      </td>
    </tr>
    <tr class="newrow">
      <td colspan="6">
      
      <h6 class="row-total">total: 0     </h6>
        <form action="upload/uploaden.php" class="dropzone dropzoneform dz-clickable" maxfiles="1" id="dropzone4">
          <input type="hidden" value="Monomeer" name="productnaam">
          <input type="hidden" value="Twan" name="klantnaam">
          <input type="hidden" value="90" name="hoogte">
          <input type="hidden" value="90" name="breedte">
          <input class="aantalinput" type="hidden" value="10" name="aantal">
          <div class="dz-default dz-message"><span><i class="fas fa-file-upload uploadicon"></i> <span class="uploadtxt">Upload je bestand(en)</span></span></div>
        </form>
      </td>
    </tr>
  </tbody>
</table>


<div class="hiddendiv">

  <div class="dz-preview dz-file-preview">
    <div class="dz-image"><img data-dz-thumbnail /></div>
    <div class="dz-details">
      <div class="dz-size"><span data-dz-size></span></div>
      <div class="dz-filename"><span data-dz-name></span></div>
    </div>
    <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
    <div class="dz-error-message"><span data-dz-errormessage></span></div>
    <span class="infoline">
      <span class="infospan bestandnaam">Bestandnaam:</span>
      <!-- <i class="fas fa-times-circle afgekeurd"></i> -->
    </span>
    <span class="infoline">
      <span class="infospan resolutie">Resolutie:</span>
      <!-- <i class="fas fa-check-circle goedgekeurd"></i> -->
    </span>
    <span class="infoline">
      <span class="infospan formaat">Formaat:</span>
      <!-- <i class="fas fa-times-circle afgekeurd"></i> -->
    </span>
    <div class="foutformaat">
      <span>Bestand heeft niet het benodigde formaat.</span>
      <span class="uploadinfobox">
        <button class="infotooltip tooltipupload" data-tooltip="Lorem ipsum">
          <i class="fas fa-info-circle"></i>
        </button>
      </span>
    </div>
    <button class="yellowbtn btn vrijgevenbtn" type="button">Bestand vrijgeven</button>
    <hr class="uploadline">
    <span class="toewijzen">Aantal</span>
    <div class="uploadcontent">
      <input type="number" value="0" min="0" class="fileinput">
    </div>
  </div>
</div>