The code counts the amount, and it is necessary that it automatically recorded this amount in another field.

var budget = document.budget.value; var sum=0; $('table tr').each(function(){ $(this) .find('input[type=text]') .each(function(){ sum+=parseInt($(this).val()); }); $(this).find('td:last').html(sum); sum=0; }); 

    2 answers 2

    You need to use .each() correctly, so read the article carefully.

    It clearly states that the method has one use case:

    .each (callback (index, domElement))

    You do not pass any parameters to the callback. So we just need to rewrite the code a bit. The markup did its, but the principle is clear:

     function getSum() { var $target = $('.term'), sum = 0; //тот кусок, который вам нужен $target.each(function(idx, item) { sum += parseInt($(this, item).val()) || 0; }); $('.sumInput').val(sum); $('.sum').text(sum); } document.getElementById('getSum').addEventListener('click', getSum, false); 
     input { display: block; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text" class="term" placeholder="Слагаемое" /> <input type="text" class="term" placeholder="Слагаемое" /> <input type="text" class="term" placeholder="Слагаемое" /> <input type="text" class="term" placeholder="Слагаемое" /> <input type="button" id="getSum" value="Посчитать" /> <input type="text" class="sumInput" placeholder="Сумма" /> <div class="sum"></div> 

      If I understand the question correctly.

      1. You have declared a variable var sum = 0; outside the .each function, so the amount is not reset.
      2. For each input you need to attach an event that tracks the change.

      Example: https://jsfiddle.net/wn9k26qw/1/

       function rowSumm($row) { var summ = 0; $row.find('input[type=text]') .each(function() { var val = parseInt($(this).val()); summ += isNaN(val) ? 0 : val; }); $row.find('td:last').html(summ); } $('table tr input[type=text]').keyup(function() { var $row = $(this).parents('tr'); rowSumm($row); }); $('table tr').each(function() { rowSumm($(this)) }); 
       input { max-width: 50px; } 
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <thead> <th>Field 1</th> <th>Field 2</th> <th>Field 3</th> <th>Field 4</th> <th>Summ</th> </thead> <tbody> <tr> <td><input type="text" value="1"></td> <td><input type="text" value="2"></td> <td><input type="text" value="3"></td> <td><input type="text" value="4"></td> <td></td> </tr> <tr> <td><input type="text" value="1"></td> <td><input type="text" value="2"></td> <td><input type="text" value="3"></td> <td><input type="text" value="4"></td> <td></td> </tr> <tr> <td><input type="text" value="1"></td> <td><input type="text" value="2"></td> <td><input type="text" value="3"></td> <td><input type="text" value="4"></td> <td></td> </tr> </tbody> </table>