How do we update a textbox on ticking checkboxes? Please see the following code, only ‘School’ gets filled on clicking the checkboxes. I would like to fill all the three words on ticking.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function updatebox()
{
var textbox = document.getElementById("list")
textbox.value = ""
if(document.getElementById('cb2').checked) {
textbox.value = "School"
}
if(document.getElementById('cb3').checked) {
textbox.value = textbox.value + " College "
}
if(document.getElementById('cb4').checked) {
textbox.value = textbox.value + " University"
}
}
</script>
</head>
<body>
<input id="cb2" type="checkbox" name="vehicle" value="School" onclick="updatebox()" /> School <br />
<input id="cb3 "type="checkbox" name="vehicle" value="College" onclick="updatebox()" /> College<br />
<input id="cb4" type="checkbox" name="vehicle" value="University" onclick="updatebox()" /> University<br />
<input id="list" type="text" name="list" />
</body>
</html>
Your script is throwing an error because you don’t have a checkbox called
"cb3"(because of a typo in your HTML, it’s either called"cb3 "— with the space at the end — or it doesn’t have an ID at all [as spaces are not valid in IDs], depending on the browser). Without the typo, it mostly works as you intended although if School isn’t checked, you get a space at the beginning and if University isn’t checked but College is, you get a space at the end.Side note #1: Your code is relying on the horror that is Automatic Semicolon Insertion. I strongly recommend not relying on it. Always include all required semicolons.
Side note #2: There are lots of ways to avoid having the space if “School” isn’t ticked. One of the easiest is just to use an array and
Array#joinwith space as the separator, like this (I’ve also added the semicolons):Live example | source
Side note #3:
labelelements can make checkboxes much easier to use by allowing clicking on the label as well as the actual box:Live example | source