There is a table, very large, with a price list of services.

<table width="100%" border="0" cellspacing="2" cellpadding="2"> <thead> <th>Предмет</th> <th>В наличии</th> <th>Цена</th> <th>Кол-во</th> <th>Общая цена</th> </thead> <tr> <td>ручка гелевая</td> <td>40шт</td> <td id="cena">5</td> <td><input id="colvo" onkeyup="summ()"></td> <td><div id="result"></div></td> </tr> <tr> <td>ручка шариковая</td> <td>40шт</td> <td id="cena">10</td> <td><input id="colvo" onkeyup="summ()"></td> <td><div id="result"></div></td> </tr> </table> 

How can we calculate the sums of individual lines without declaring a variable for each of them? I repeat: VERY big table.

  • @ReeQx, If you are given an exhaustive answer, mark it as correct (click on the check mark next to the selected answer). - Vitalina

3 answers 3

I would do this ( http://jsfiddle.net/alpha9000/Lazu596w/1/ ):

Set the cell with the sum control class and the date attribute with the sum, like this:

 <td class="js-summ" data-summ="100">100 рублей</td> 

Make an array of the necessary lines and count them:

 var rows = [1,2,7,9]; var $rows = $('table').find('tr'); var result = 0; $.each(rows,function(i,e){ var $target = $rows.eq(e).find('.js-summ'); var thisResult = parseFloat($target.attr('data-summ')); if (typeof(thisResult) === 'number') { result += thisResult; } }); console.log(result); // result here 

PS Do not forget that the lines are counted from zero. ;)

    Redo the table. Id on the page must be unique. You don’t need it at all, replace it with name. Wrap each line as follows <form>код строчки</form>

     <form> Доступно <output name='dostupno'>40</output><br> Цена <output name='cena'>10</output><br> Количество <input name='colvo' type='number' oninput='colvo.value = Math.min(colvo.value, dostupno.value);result.value = cena.value * colvo.value'><br> Сумма <output name='result'>0</output><br> </form> 

      Replace onkeyup="summ()" with onkeyup="summ(this)" .
      And add the script:

       <SCRIPT> function summ(o){ r=o.parentElement.parentElement; r.cells(4).children(0).innerHTML=parseInt(r.cells(2).innerHTML)*(o.value==""?0:parseInt(o.value)) } </SCRIPT>