skip to Main Content

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 class="size_qty" type="number" min="0" name="numberInputs" value="0" onchange='sum_row_qty(this)'></td>
  <td><input class="size_qty" type="number" min="0" name="numberInputs" value="17" onchange='sum_row_qty(this)'></td>
  <td class="total">0.00</td>
</tr>

Fiddle
Thank you!

2

Answers


  1. 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 class="size_qty" type="number" min="0" name="numberInputs" value="0" onchange='sum_row_qty(this)'></td>
      <td><input class="size_qty" type="number" min="0" name="numberInputs" value="17" onchange='sum_row_qty(this)'></td>
      <td class="total">0.00</td>
    </tr>
    </table>
    Login or Signup to reply.
  2. you can also do it like this with pure js, no jquery needed

    <tr>
      <td><input class="size_qty" type="number" min="0" name="numberInputs" value=0 onchange='sum_row_qty(this)'></td>
      <td><input class="size_qty" type="number" min="0" name="numberInputs" value=17 onchange='sum_row_qty(this)'></td>
      <td class="total">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)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search