0

I'm having dynamic table view with dynamic data and 4 other extra fields to input some values.and one field to show sum of other four inputs.

But my jquery code works only for first row of table.

My table is dynamic with some other fields that i didn't mention here. This is in while loop. and my first row is only works as per my jquery script.other rows are not working.

$(document).ready(function() {
  sum();
  $("#paye, #ee_ni, #er_ni, #pension").on("keydown keyup", function() {
    sum();
  });
});

function sum() {
  var paye = document.getElementById('paye').value;
  var ee_ni = document.getElementById('ee_ni').value;
  var er_ni = document.getElementById('er_ni').value;
  var pension = document.getElementById('pension').value;
  var result = parseInt(paye) + parseInt(ee_ni) + parseInt(er_ni) + parseInt(pension);
  if (!isNaN(result)) {
    document.getElementById('total_cost').value = result;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td align="center"><input type="text" name="paye" id="paye"></td>
    <td align="center"><input type="text" name="ee_ni" id="ee_ni"></td>
    <td align="center"><input type="text" name="er_ni" id="er_ni"></td>
    <td align="center"><input type="text" name="pension" id="pension"></td>
    <td align="center"><input type="text" name="total_cost" id="total_cost"></td>

  </tr>
</table>
j08691
  • 204,283
  • 31
  • 260
  • 272
amit sutar
  • 541
  • 2
  • 11
  • 37
  • 1
    Please update the snippet I made you with relevant code and more rows. You MUST have unique IDs so change to class and use jQuery: `$(".paye").each(function() { var paye = $(this).val(), ee_ni=$(this).closest("tr").find(".ee_ni").val()...` – mplungjan Apr 23 '18 at 14:33
  • 1
    This being in a loop and it only working for the first row, you are duplicating ids. Use classes instead with contextual lookups. – Taplar Apr 23 '18 at 14:34

0 Answers0