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. The issue I am having is when I end my if statements with document.getElementById("subtotal").value = total
it isn't populating the textbox. If I insert an alert
or document.write
statement then it will populate it. 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.