Reputation: 349
I'm just trying to get this checkbox to alert a message after it is checked and after it is unchecked by running a function in Javascript. I can get it to display the "checked" message but can't get the "unchecked" alert to come up.
<input type="checkbox" id="chbx" onchange="foo()">
<script type="text/javascript">
var checkbox = document.getElementById("chbx");
function foo(){
if(checkbox.checked=true){
alert("Checked!");
}
else {
alert("UnChecked!");
}
};
</script>
Upvotes: 3
Views: 25681
Reputation: 710
You made the commonly made mistake of using a single =
this actual sets the checkbox.checked
to true. If you want to make a comparison make sure to use a double ==
.
Also, there are only two options for a checkbox; so if it's not on it's off:
This is what I would have done:
<input type="checkbox" id="chbx" onchange="checkbox_changed()">
<script type="text/javascript">
var checkbox = document.getElementById("chbx");
function checkbox_changed() {
if (checkbox.checked == true) {
alert("Checked!");
} else {
alert("UnChecked!");
}
}
</script>
Upvotes: 2
Reputation: 40393
You've got single-equals instead of double-equals in your if statements:
if (checkbox.checked=true) {
should be
if (checkbox.checked == true) {
or just
if (checkbox.checked) {
Upvotes: 7
Reputation: 5287
You are not comparing values using =
. Needs to be at least ==
, better ===
if(checkbox.checked === true) {}
or, simplified
if(checkbox.checked) {}
Upvotes: 4