2

I have multiple dropzone elements in which previews of an uploaded image are shown. Inside those previews I added input fields with a + and - button next to it by clicking you can add or substract the value of that input field. This works fine, but now I need to get the sum of all input fields (only in that dropzone, so only in that iteration of the each function.

On Stack Overflow I found a function that I tweaked a bit to get the following code:

$plusbtn.click(function(e) {
    e.preventDefault();
    let currentValue = parseInt($input.val());
    $input.val(currentValue + 1);

    $preview.each(function(){
        currentValue += +$input.val();
    });
    console.log(currentValue);
});

currentValue shows a number in the console increased by 2 every time I click the + button instead of the total sum. For example 1-3-5-7-9-11.

This is the entire code inside the each function.

$('.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 $thisdropzone = $el;

    $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
        success: function (file, response) {
            // alert('test');
            let file_meta = JSON.parse(response);
            let $preview = $(file.previewElement);
            let $plusbtn = $preview.find('#plusupload');
            let $minbtn = $preview.find('#minupload');
            let $input = $preview.find('.fileinput');

            // Input plus min
            $plusbtn.click(function(e) {
                e.preventDefault();
                let currentValue = parseInt($input.val());
                $input.val(currentValue + 1);

                $preview.each(function(){
                    currentValue += +$input.val();
                });
                console.log(currentValue);
            });

            $minbtn.click(function(e) {
                e.preventDefault();
                let currentValue = parseInt($input.val());
                $input.val(currentValue - 1);

                $input.each(function(){
                    currentValue += -$(this).val();
                });
            });

            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');
        },
    })
});

How can I get the sum of all input fields per each iteration?

Here is a snippet:

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 $thisdropzone = $el;
    
    $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');
        let $input = $preview.find('.fileinput');

        // Input plus min
        $plusbtn.click(function(e) {
            e.preventDefault();
            let currentValue = parseInt($input.val());
            let sum = 0;
            $input.val(currentValue + 1);

            $preview.each(function(){
                currentValue += +parseInt($input.val());
            });
            console.log(currentValue);
        });

        $minbtn.click(function(e) {
            e.preventDefault();
            let currentValue = parseInt($input.val());
            $input.val(currentValue - 1);

            $input.each(function(){
                currentValue += +$(this).val();
            });
        });
            

            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">
            <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">
               <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">
            <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">
               <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">
   <button class="plusminupload" id="minupload">−</button>
                                                                <button class="plusminupload" id="plusupload">+</button>
      </div>
    </div>
  </div>

0

2 Answers 2

2
+50

Please have a look a this fiddle https://jsfiddle.net/k5ut29os/

I added a variable in the dropzone's foreach to hold the total, and a function to update it.

let this_dropzone_sum = 0;
function updateTotal(){
    this_dropzone_sum = 0;
    $el.find('.uploadcontent input').each( function(){
        this_dropzone_sum += parseInt($(this).val());
  });
}

Then I called the function in the two buttons (plus/minus)

$plusbtn.click(function(e) {
    e.preventDefault();
    let currentValue = parseInt($input.val());
    let sum = 0;

    // update input
    $input.val(currentValue + 1);

    updateTotal();
    console.log(this_dropzone_sum);

});

Hope it answers your question.

Sign up to request clarification or add additional context in comments.

3 Comments

Just to add to the answer of @pietro : Your preview.each doesn't do anything with the value of the input - you just add the current input value again for each input.
@Pietro I don't see the total being updated in the fiddle you posted.
It's in the console. I'll update the fiddle to write into that span (I used it for a moment, but I forgot to remove it)
-1

I don't think I understand your meaning you want to know hoy many inputs fields are in the page?

if so you can do by document.querySelectorAll('input').length

1 Comment

You want to get the sum of the value of the inputs of so... do somthing like this: inputs.map((obj)=> obj.value).reduce((a,b) => a + b, 0)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.