Reputation: 21
I am pulling records from a db, displaying them in a table rows with form input fields. That means there will be multiple rows as seen in the sample html code below. I want to use javascript only. The idea is that when a user enters a quantity, it gets multiplied by the unit price and the result displayed in the sub total field. I am not JS developer, I searched and found the below code which is close to what I need. I will appreciate if someone can make some suggestions so as to get this code work.
<SCRIPT language="JavaScript">
<!--
function calculate() {
var Quantity = document.getElementsByName("Quantity").value;
var unitPrice = document.getElementsByName("unitPrice").value;
var total = 0;
for (var i = 0; i < Quantity.length; i++) {
total += parseInt(Quantity[i].value) * parseInt(unitPrice[i]);
}
document.getElementsByName("subtotal").value = total;
}
</SCRIPT>
<table>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2"/>
<input name="subtotal" size="2"/>
</td>
</tr>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2"/>
<input name="subtotal" size="2"/>
</td>
</tr>
</table>
Upvotes: 1
Views: 120
Reputation: 10208
A few things: a) document.getElementsByName("")
returns a NodeList Collection of elements, so you cannot get the value of each input like that, you'll have to get them inside the for loop; b) then you also need to get the value of each unitPrice[i]
inside the loop before parsing it and c) the total should be reset after each iteration, so can just have it inside the loop. See below:
function calculate() {
var Quantity = document.getElementsByName("Quantity");
var unitPrice = document.getElementsByName("unitPrice");
for (var i = 0; i < Quantity.length; i++) {
if (!Quantity[i].value) continue; // prevent NaN
let total = parseInt(Quantity[i].value) * parseInt(unitPrice[i].value);
document.getElementsByName("subtotal")[i].value = total;
}
}
<table>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2" />
<input name="subtotal" size="2" />
</td>
</tr>
<tr>
<td>
<input onblur="calculate()" name="Quantity" size="2" />
<input name="unitPrice" value="5" size="2" />
<input name="subtotal" size="2" />
</td>
</tr>
</table>
In order to avoid getting NaN
for the result which does not have any value, you can add if (!Quantity[i].value) continue;
as the first line in the for loop, that should prevent it.
Upvotes: 1