Jorge
Jorge

Reputation: 37

How would I add same type of inputs value from a different row?

Initially I have rows of object with an input of "subtotal" on each of the row. First I loop through each of the input with an id of subtotal and was able to get the value of each. Now i wanted to add all values and place it somewhere in an element total. How am i able to do it?

 $("input[id*='subtotal'").each(function(index) {
    console.log($(this).val();
 })

Upvotes: 0

Views: 28

Answers (1)

Nidhin Joseph
Nidhin Joseph

Reputation: 10227

Try this.

function onChange() {
  let sum = 0;
  $("input[subtotal]").each(function(index) {
    let v = parseInt($(this).val());
    if (v > 0) {
      sum += v;
    }
  });
  document.getElementById('sum').innerHTML = sum;
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

<input type="text" subtotal onkeyup="onChange()" />
<input type="text" subtotal onkeyup="onChange()" />
<input type="text" subtotal onkeyup="onChange()" />
<input type="text" subtotal onkeyup="onChange()" />

<div id="sum">0</div>

Upvotes: 1

Related Questions