talkpoppycock talkpoppycock - 6 months ago 9
HTML Question

Use the same calculation n number of times

I have the following three inputs:

<input type="text" name="cost" id="cost" oninput="calculate()" value="">
<input type="text" name="quantity" id="quantity" oninput="calculate()" value="">
<input type="text" name="total" id="total" value="" readonly >


When the price and quantity are entered the following function calculates the total:

function calculate() {
var price = document.getElementById('cost').value;
var num = document.getElementById('quantity').value;
var total1 = document.getElementById('total');
var myResult = price * num;
total.value = myResult;
}


The three inputs can be repeated an unknown number of times depending on the number of entry's in a database table. I would like to use the same function on all the inputs, but despite searching for hours, I'm no further forward. I believe I will need to use getElementsByName. Any help would be very much appreciated.

Answer

Group your inputs together. So given one input, you can easily find the other inputs. Then use calculate(this) instead of calculate(). this in this case refers to the input that was changed.

function calculate(e) {
  var div = e.parentNode;
  var c = div.querySelector('.cost').value;
  var q = div.querySelector('.quantity').value;
  div.querySelector('.total').value = c * q;
}
<div>
  <input type="text" class="cost" oninput="calculate(this)" value="">
  <input type="text" class="quantity" oninput="calculate(this)" value="">
  <input type="text" class="total" value="" readonly>
</div>
<div>
  <input type="text" class="cost" oninput="calculate(this)" value="">
  <input type="text" class="quantity" oninput="calculate(this)" value="">
  <input type="text" class="total" value="" readonly>
</div>
<div>
  <input type="text" class="cost" oninput="calculate(this)" value="">
  <input type="text" class="quantity" oninput="calculate(this)" value="">
  <input type="text" class="total" value="" readonly>
</div>

Comments