Make sure to get a reference to the checkbox using the proper API:
// Get a reference to the element the proper way:
var checkbox = document.querySelector("input[type='checkbox']");
checkbox.addEventListener('change', function(){
switch(this.value){
case "on":
this.value = "off";
break;
case "off":
this.value = "on";
break;
}
console.log(this.value)
});
<input type="checkbox" name = "checkbox" checked = "checked" value = "on">
With that said, it's not super useful to change the value of a checkbox because it's checked. The usual way a checkbox is used is either to submit its value
as part of a form
submission or to use as a Boolean indicator of some state for "in-page" behavior. You generally don't want or need to change the value
of a checkbox, instead you simply want to know if it is checked, which can be done by looking at its .checked
property and making decisions based on that. A checkbox will have a checked
property value of true
when it's been checked and false
when it isn't.
// Get a reference to the element the proper way:
var checkbox = document.querySelector("input[type='checkbox']");
checkbox.addEventListener('change', function(){
if(this.checked){
console.log("Checkbox is checked! Do something about it!");
} else {
console.log("Forget it. Checkbox wasn't checked.");
}
});
<input type="checkbox" name = "checkbox" value = "on">