3

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>
1
  • 1
    You need to use == or ===, as what you're doing is setting the value (true every time). The second form is best. (Nevermind, I see you edited out the incorrect syntax.) Commented Oct 27, 2012 at 17:52

3 Answers 3

7

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) {
Sign up to request clarification or add additional context in comments.

Comments

4

You are not comparing values using =. Needs to be at least ==, better ===

if(checkbox.checked === true) {}

or, simplified

if(checkbox.checked) {}

5 Comments

@DanBarzilay: excuse me ? Why not, === just compares type AND value so its much more precise. Even if it makes no difference here, I just mentioned its "better".
=== is for type and a boolean is a boolean it doesn't matter if its true or false.. it should be ==
@DanBarzilay: I don't agree with you. Just for convinience === should always be used in this language to avoid crucial errors/confusion with types
@DanBarzilay - It can be. Crockford, for one, says always use ===. So it's not "wrong" or "bad" in this case, it just happens that both are equivalent and work in this situation.
@JaredFarrish Sorry, my mistake.
2

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>

1 Comment

You're making the same mistake the OP did with the condition (a single =).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.