Home > database >  How to sum this table's column's values onchange?
How to sum this table's column's values onchange?

Time:09-16

I 'm not sure how to update the row total as each of these values change.I'm getting $ is not defined", obviously because I still haven't learned it and I could use some help.

function sum_row_qty(el) {
  let rowTotal = 0
  let parent = $(el).closest('tr')
  parent.find('.size_qty').each(function() {
    rowTotal  = $('.size_qty').val();
  })
  console.log(rowTotal)
}
<tr>
  <td><input  type="number" min="0" name="numberInputs" value="0" onchange='sum_row_qty(this)'></td>
  <td><input  type="number" min="0" name="numberInputs" value="17" onchange='sum_row_qty(this)'></td>
  <td >0.00</td>
</tr>
Fiddle Thank you!

CodePudding user response:

you can also do it like this with pure js, no jquery needed

<tr>
  <td><input  type="number" min="0" name="numberInputs" value=0 onchange='sum_row_qty(this)'></td>
  <td><input  type="number" min="0" name="numberInputs" value=17 onchange='sum_row_qty(this)'></td>
  <td >0.00</td>
</tr>

use getElementsByClassName then run a loop since you have multiple elements with the same class

function sum_row_qty() {
  let rowTotal = 0
  const td = document.getElementsByClassName("size_qty");
  for (let i = 0; i < td.length; i  ) {
    rowTotal  = parseFloat(td[i].value);
  }
  console.log(rowTotal)
}

CodePudding user response:

You have multiple options to fix this. Make sure you have included jquery to the page. Another option is simply use pure JS too as it's not that complicated and doesn't require jquery.

You will see similar code as the jquery with the addition of parseFloat, that way it converts the input to a float instead of a string.

function sum_row_qty(el) {
  let rowTotal = 0
  let parent = el.closest("tr")
  parent.querySelectorAll('.size_qty').forEach(function(e){
    rowTotal  = parseFloat(e.value)
  })
  console.log(rowTotal)
}
<table>
<tr>
  <td><input  type="number" min="0" name="numberInputs" value="0" onchange='sum_row_qty(this)'></td>
  <td><input  type="number" min="0" name="numberInputs" value="17" onchange='sum_row_qty(this)'></td>
  <td >0.00</td>
</tr>
</table>

  • Related