6

Clicking checkbox should give alert checked if checked and give alert not checked if not. Here is the code:

<input type = "checkbox" id = "all" value="all" /> MyCheckbox

 <script src="jquery-2.1.4.js"></script>
<script type="text/javascript">
    $("input[type=checkbox]").click(function(){
    if ($(this).attr("checked")) {   
alert("checked");
}
else{
alert("not checked");
}
});
</script>

Initially checkbox is unchecked. As soon as I click it, debugger shows it checked value true. Now control should enter if{} block as its value is true but its entering in else{} block. (Am using breakpoints).

Why this is happening. Pls help am trying for hours.

mustafa1993
  • 541
  • 1
  • 5
  • 17
  • 2
    You can also use `.prop()`. A good answer about the difference between `attr()` and `prop()` can be found [here](http://stackoverflow.com/questions/5874652/prop-vs-attr) – dingo_d Sep 06 '15 at 09:53
  • How not? You can use `.prop("checked", true)` to check if the checkbox is checked. *EDIT*: Ok, the comment above was removed. This comment was aimed at the previous one... – dingo_d Sep 06 '15 at 09:56
  • http://api.jquery.com/prop/ There is even example on the page which shows difference between using of attr() and prop(). – sinisake Sep 06 '15 at 09:57

3 Answers3

1

The problem is that you are checking checked attribute which is not going to be removed or added when checked status changes. This is a nuance you should be aware about properties and attributes. You need to compare checked property of the checkbox element, not attribute.

Also it's better to use change event handler (because you can check checkbox not only with mouse click but with keyboard too).

$("input[type=checkbox]").change(function() {
    if (this.checked) {
        alert("checked");
    }
    else {
        alert("not checked");
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = "checkbox" id = "all" value="all" /> MyCheckbox
dfsq
  • 191,768
  • 25
  • 236
  • 258
1

This :

$(this).attr("checked") //in old versions of jquery this yield "checked" , 

Yields undefined which is a Falsy statement.

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set

You can either use :

if ($(this).is(":checked"))

or

$(this).prop("checked")
Royi Namir
  • 144,742
  • 138
  • 468
  • 792
0

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

NubPro
  • 497
  • 2
  • 9