0

I'm having a problem with this one:

if($("#Autotag").is(":checked"))
{
alert("Just to check if it works");
}

But it won't give me the alert dialog while it's checked! I've been looking for right answers. All the other codes I've written does work but not this one.

jsFiddle ain't giving me any hints as person told me to try... I've also been reading this How to: jQuery how to

8
  • 2
    how do you run this code? Commented Sep 5, 2013 at 18:14
  • document.getElementById('Autotag').checked is FAR more efficient Commented Sep 5, 2013 at 18:16
  • Is it checked by default or are you trying to check it after the page loads without encasing it in change evnt Commented Sep 5, 2013 at 18:16
  • 1
    @Kolink OP wasn't asking for an optimization solution. Commented Sep 5, 2013 at 18:16
  • @Blazemonger That's why it's a comment, not an answer ;) Commented Sep 5, 2013 at 18:50

2 Answers 2

3

That code will not run when the person checks the checkbox, it will just tell you the state of the checkbox at that moment in time it has run.

If you want to know when it is checked, you need to listen for the change event. The following code assumes you call this onready or after the element is added to the page.

$("#Autotag").on("change", function () {
    if($(this).is(":checked")) {
        alert("Just to check if it works");
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

You made it before me, here is the fiddle to support your answer.
1

You need to be calling this inside a change event, instead of just calling it once

$("#Autotag").change(function() {
  var $this = $(this);
  if ( $this.is(":checked") ) {
    alert("This should work for you");
  }
});

2 Comments

While I appreciate the fact that you cached the result of $(this), it's still moot when compared to this.checked ;)
Not a problem, and its force of habit to cache things anymore

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.