user2538370
user2538370

Reputation:

Why not working check checkbox?

Code:

<input type="checkbox" id="test1" class="check" checked="">
<input type="checkbox" id="test2" class="check" checked="">
<input type="checkbox" id="test3" class="check" checked="">
<input type="checkbox" id="test4" class="check" checked="">

    <button class="start">Click</button>

$(".start").click(function(){

alert($("#test1").attr("checked"));

});

Why if i delete check on checkbox test1 alert show checked ?

Test on JsFiddle here

Upvotes: 2

Views: 745

Answers (4)

user1864610
user1864610

Reputation:

You're confusing .attr and .prop. Here you should be using .prop:

alert($("#test1").prop("checked"));

An attribute of an element is something it that is set by the markup - you can't change it. A property reflects the state of it now. There was some confusion in the implementation in earlier versions of jQuery which has now been resolved. As a result some online resources still have it wrong.

Upvotes: 1

Sergio
Sergio

Reputation: 28837

If you want to run the alert if the check box is checked use this:

if ($("#test1").is(':checked') ) {alert("yes")}

Example here

$(".start").click(function(){
   if ($("#test1").is(':checked') ) {alert("yes")}    
});

Upvotes: 2

obecker
obecker

Reputation: 2377

I suppose this is because you are testing the static HTML.

If you want to test the checked property use instead

alert($("#test1").prop("checked"));

This gives you either trueor false

BTW: the attribute should be either checked="checked" or not present at all.

Upvotes: 1

kalley
kalley

Reputation: 18462

You need to use .prop instead of .attr.

http://api.jquery.com/prop/

The pertinent part:

elem.checked                     true (Boolean) Will change with checkbox state
$(elem).prop("checked")       true (Boolean) Will change with checkbox state
elem.getAttribute("checked")      "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked") (1.6)     "checked" (String) Initial state of the checkbox; does not change
$(elem).attr("checked") (1.6.1+)  "checked" (String) Will change with checkbox state
$(elem).attr("checked") (pre-1.6) true (Boolean) Changed with checkbox state

Upvotes: 2

Related Questions