我无法使用输入名称抓取多个输入并向其添加乘法,如下所示。有没有其他方法可以在不使用 getElementById 的情况下执行此操作?
<input type="number" name="test1" id="RoundInput1">
<input type="number" name="test2" id="RoundInput2">
<button onclick="GetTheResults()">Try it</button>
<p id="demo">Click the button to change the text in this paragraph.</p>
<script>
x = document.getElementsByName("test1").value;
z = document.getElementsByName("test2").value;
var Savings = x + z;
function GetTheResults() {
document.getElementById("demo").innerHTML = Savings;
}
</script>
请注意我也尝试了以下内容:
x = document.getElementsByName("test1")[0].value;
z = document.getElementsByName("test2")[0].value;
答案 0 :(得分:2)
<input type="number" name="test1" id="RoundInput1">
<input type="number" name="test2" id="RoundInput2">
<button onclick="GetTheResults()">Try it</button>
<p id="demo">Click the button to change the text in this paragraph.</p>
<script>
function GetTheResults() {
x = document.getElementsByName("test1")[0].value;
// x = document.getElementById("RoundInput1").value;
z = document.getElementsByName("test2")[0].value;
// z = document.getElementById("RoundInput2").value;
var Savings = parseInt(x) + parseInt(z);
document.getElementById("demo").innerHTML = Savings;
}
</script>
答案 1 :(得分:1)
您需要将document.getElementsByName()
次调用移入该功能。您还需要使用parseInt()
将输入转换为整数值。正如名称getElementsByName
所暗示的那样,返回的值是所有找到的元素的数组;在您的情况下,您将需要访问返回数组的第一个元素以供添加。
<强>代码强>
function GetTheResults() {
x = parseInt(document.getElementsByName("test1")[0].value);
z = parseInt(document.getElementsByName("test2")[0].value);
var Savings = x + z;
document.getElementById("demo").innerHTML = Savings;
}
&#13;
<input type="number" name="test1" id="RoundInput1">
<input type="number" name="test2" id="RoundInput2">
<button onclick="GetTheResults()">Try it</button>
<p id="demo">Click the button to change the text in this paragraph.</p>
&#13;