Solution 1 :

You have to use the jQuery each function. your final code will be like this

$(document).ready(function() {
   $('.margin .custom-input').change(function() {  
      updateTotal();
   });

   var updateTotal = function () {
        var total = 0;
        $('.margin .custom-input').each(function() {
            total += parseInt($(this).val());
        });

         $(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
   };
});

Or, you just directly get the value of active input so that no need to implement for loop. like this

$(document).ready(function() {
   var total = 0

   $('.margin .custom-input').change(function() {  
       total += $(this).val()
      $(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
   });

});

Solution 2 :

jQuery does have foreach support, in form of the .each() function:

var sum = 0;
$('.margin .custom-input').each(function() {
    sum += parseInt($(this).val());
});

Problem :

I have 48 inputs, and for each input I need to get its value and add it to the total sum. Currently I am only getting the values of two inputs and adding them but how would it be better to make this a “foreach function”

$(document).ready(function() {
   $('.margin .custom-input:nth-child(1)').change(function() {  
      updateTotal();
   });
   $('.margin .custom-input:nth-child(2)').change(function() {
      updateTotal();
   });

   var updateTotal = function () {
      var input1 = parseInt($('.margin .custom-input:nth-child(1)').val());
      var input2 = parseInt($('.margin .custom-input:nth-child(2)').val());

      var total = input1 + input2;

      $(".marginAttachment").text("Durchschn. Attachmentniveau = " + total + "mm");
   };
});
<div class="margin">
   <input class="custom-input" type="text" value="0">
</div>

Comments

Comment posted by Luca Kiebel

Please show an effort at solving your question, and how that isn’t working.

Comment posted by api.jquery.com/jquery.each

api.jquery.com/jquery.each

By

Leave a Reply

Your email address will not be published. Required fields are marked *