0

Hello all,
well i have a problem, but it sorta works. Here is my code.

var toggleState = 0
function toggleMe() {
    if(toggleState == 0) {
        alert("Checked");
        toggleState = 1;
    } else {
        alert("Unchecked");
        toggleState = 0;
    }
}

HTML

<input type="checkbox" onclick="toggleMe()" />Toggle me
<input type="checkbox" onclick="toggleMe()" />Toggle me

The problem is that when i check box 1, i get an alert. When i click it gain, nothing. Now when i click it a third time for it to uncheck, then i get the alert and it works fine where i can do it on and off with the alerts. The only thing is now its backwards. Now, if i check the first one, alert works. If i do the second one while the first one is checked then again nothing, then it works on the 2nd click. I have tried if(this.attribute = "checked") { do something} else { if(this.attribute = "unchecked") { alert unchecked} but nothing. Im just really confused.

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by fobos
0

Fobos,

The trouble is you have one variable, toggleState , being influenced by two checkboxes.

In fact, you generally don't need variable(s) to record checkbox state (checked or unchecked) because you can enquire the checkboxes themselves at any time. (They know their own state with incredible reliability!)

Try this:

function alertMe(checkBox) {
    alert(checkBox.checked ? "Checked" : "Unchecked");
}
<input type="checkbox" onclick="alertMe(this)" />Alert me
<input type="checkbox" onclick="alertMe(this)" />Alert me

Airshow

Edited by Airshow: n/a

0

Wow, i cant stop laughing how i overlooked doing it that way. I really appreciate the help Airshow.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.