[英]Why can't I end my if statement with document.getElementById(“ID”).value = var?
I am writing a price checkbox page for my web programming class using javascript where if you check on the boxes and click subtotal, the price is put into a textbox. 我正在使用javascript为我的Web编程类编写一个价格复选框页面,如果您选中这些复选框并单击小计,则价格会放入文本框。 The issue I am having is when I end my if statements with
document.getElementById("subtotal").value = total
it isn't populating the textbox. 我遇到的问题是当我用
document.getElementById("subtotal").value = total
结束if语句时,它没有填充文本框。 If I insert an alert
or document.write
statement then it will populate it. 如果我插入一个
alert
或document.write
语句,那么它将填充它。 Any idea what I am missing? 知道我缺少什么吗? here is my code with the alerts in place (that I don't want):
这是我的代码,其中有警报(我不想要):
<!DOCTYPE html>
<head>
<title> Price Checkbox </title>
<meta charset = "utf-8" />
<script>
var total, a = 0;
</script>
<script type = "text/javascript">
function subtotal1()
{
if (document.getElementById('apple').checked)
{
total = a + .59;
a = total;
document.getElementById("subtotal").value = total
alert(total);
}
if(document.getElementById('orange').checked)
{
total = a + .49;
a = total;
document.getElementById("subtotal").value = total
alert(total);
}
if(document.getElementById('banana').checked)
{
total = a + .39;
a = total;
document.getElementById("subtotal").value = total
alert(total);
}
}
</script>
</head>
<body>
<form id = "myForm" action = "">
<p>
<label> <input type = "checkbox" id = "apple"/>
apple $.59 </label>
<br />
<label> <input type = "checkbox" id = "orange"/>
orange $.49 </label>
<br />
<label> <input type = "checkbox" id = "banana"/>
banana $.39 </label>
</p>
<button onclick = "subtotal1()">Submit</button>
<p></p>
<input type="textbox" id="subtotal"/>
</form>
</body>
I suggest a different approach. 我建议使用另一种方法。 Add an event when the checkbox is clicked.
单击复选框时添加事件。 This way you can also see what is happening and not leave it when submitting the form.
通过这种方式,您还可以查看正在发生的事情,而在提交表单时却不会离开。 Try this code:
试试这个代码:
<body>
<form id = "myForm" action = "">
<p>
<label> <input type = "checkbox" id = "apple" onclick = "subtotal1();"/>
apple $.59 </label>
<br />
<label> <input type = "checkbox" id = "orange" onclick = "subtotal1();"/>
orange $.49 </label>
<br />
<label> <input type = "checkbox" id = "banana" onclick = "subtotal1();"/>
banana $.39 </label>
</p>
<button>Submit</button>
<p></p>
<input type="textbox" id="subtotal"/>
</form>
</body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.