Am trying to multiply two cells in HTML table. Here below the code I created:
function multiply() {
var u_price = parseFloat(document.getElementsByName("u-price"));
var s_meter = parseFloat(document.getElementsByName("s-meter"));
var t = u_price * s_meter;
document.getElementById("tot-price").value = t.toFixed(3);
}
<tr>
<td><input type="text" class="input-box" name="u-price" value="0" onKeyUp="multiply();"></td>
<td><input type="text" class="input-box" name="s-meter" value="1" onKeyUp="multiply();"></td>
<td><input type="text" class="input-box" name="tot-price" id="tot-price" disabled></td>
</tr>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
The value returned is NaN.
Can you please advise on how to handle this.
Thank you in advance!
CodePudding user response:
A couple changes needed:
getElementsByName
returns an array of elements matching the name parameter.
So if you're using this method, you should change it togetElementsByName[0]
and make sure you only have one element that matches (i.e. - no other elements with a matching name).You forgot
.value
So your function should look like this -
function multiply() {
var u_price = parseFloat(document.getElementsByName("u-price")[0].value);
var s_meter = parseFloat(document.getElementsByName("s-meter")[0].value);
var t = u_price * s_meter;
document.getElementById("tot-price").value = t.toFixed(3);
}
CodePudding user response:
document.getElementsByName
returns an array of elements by that name and hence we need to access the value of the first element of that array.
Instead of document.getElementsByName("u-price")
,
You will have to use document.getElementsByName("u-price")[0].value
to get the value.