[英]Total price calculation with Javascript
Am trying to multiply two cells in HTML table.我试图将 HTML 表中的两个单元格相乘。 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>
The value returned is NaN.返回的值为 NaN。
Can you please advise on how to handle this.您能否就如何处理这个问题提出建议。
Thank you in advance!先感谢您!
A couple changes needed:需要进行一些更改:
getElementsByName
returns an array of elements matching the name parameter. getElementsByName
返回与 name 参数匹配的元素数组。
So if you're using this method, you should change it to getElementsByName[0]
and make sure you only have one element that matches (ie - no other elements with a matching name).因此,如果您使用此方法,则应将其更改为getElementsByName[0]
并确保您只有一个匹配的元素(即 - 没有其他具有匹配名称的元素)。
You forgot .value
你忘了.value
So your function should look like this -所以你的 function 应该是这样的 -
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);
}
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. document.getElementsByName
返回该名称的元素数组,因此我们需要访问该数组的第一个元素的值。
Instead of document.getElementsByName("u-price")
,而不是document.getElementsByName("u-price")
,
You will have to use document.getElementsByName("u-price")[0].value
to get the value.您将不得不使用document.getElementsByName("u-price")[0].value
来获取价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.