0

I have the following code:

$("#chkbx_first").change(function () {
if ($(this).attr("checked")) {
    alert("Check Box Selected"); //do something when checked
} else {
    alert("Check Box Unselected"); //do something when cleared
}

The problem is that despite on the checkbox stste the second allert appears all the time - "Check Box Unselected". Why the first alert doesn't appear ?

Is there another approaches to track the CHECK event? Thanx.

3 Answers 3

2
$(this).attr("checked");

will not work with from jQuery 1.6.

Instead use

jquery .prop().

$(this).prop("checked");

DEMO

or

jquery .is().

$(this).is(':checked')

DEMO

or

this.checked

DEMO

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

Comments

1

Try if (this.checked) or Use .prop()

$("#chkbx_first").change(function () {
    if (this.checked) { // or if($(this).prop("checked")){
        alert("Check Box Selected"); //do something when checked
    } else {
        alert("Check Box Unselected"); //do something when cleared
    }
}

Read Attributes vs. Properties

2 Comments

I got the message - "'this' souldn't be used in the global context"
@AndreyLangovoy than use if($(this).prop("checked")){ n make na fiddle
1

Checked is a property not an attribute of a checkbox, use .prop() instead

$(this).prop('checked')

You could use alse the native DOM (faster)

this.checked

Comments

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.