2

I am trying to test the status of a checkbox upon its click.

My problem is that it always reports as true as it reports the status after the change event has taken place and not before.

Is there anyway I can test before the change.

Current code using jQuery - the checkboxes all of class 'package':

$(".package").click(function(){
    if($(this).is(":checked")){
        alert($(this).attr("checked"));
    }
});

This always returns true even if selecting a checkbox that is not currently checked.

EDIT : Ok seems there was some old js interfering with the process, after cleaning that up the click function did indeed work. Thanks all.

4
  • You can use the change event instead: $(".package").change(function() { // value has changed }); Commented Apr 4, 2012 at 11:34
  • Unfortunately the change event causes the same issues (in FF atleast, atm i've not expanded the testing) Commented Apr 4, 2012 at 11:40
  • Hiya, try this: stackoverflow.com/questions/4817735/… cheers! Commented Apr 4, 2012 at 11:43
  • Is there a way to see the affected fragment of the actual HTML? Commented Apr 4, 2012 at 12:45

3 Answers 3

2

Using the onchange event on a checkbox is not cross-browser (hello IE! And yes, even with jQuery).

The following works:

$('.package').click(function() {
    console.log(this.checked) // There is no need for jQuery here
})

Logs 'true' when you check the checkbox, and 'false' when you uncheck it.

And seriously, using $(this).attr('checked') or $(this).is(':checked') is just jQueryception for nothing.

Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately still reports true for everything
I'd like to have more information about your environment then :)
1

You can use the change event instead, this way you are sure the previous checked state is always the oposite of what you read now

$(".package").change(function() {
    alert($(this).attr("checked"));
});

1 Comment

Unfortunately still reports true for everything
1

The click event fires before the actual textbox change takes place, you need to subscribe to the change event:

$(".package").change(function(){
    if($(this).is(":checked")){
        alert($(this).attr("checked"));
    }
});

Edit: Try querying the actual Javascript object itself, should work

$(".package").change(function(){
    if(this.checked){
        alert(this.checked);
    }
});

2 Comments

Unfortunately still reports true for everything, even when not previously checked
@mr12086 check my edit, that works for me :). If it doesn't work for you, could you please show us your HTML?

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.