2

I have a simple script that works only once. My script will check a checkbox if I click anywhere inside a table row. However, if I click inside the row a second, third, etc. time, then it doesn't work anymore. Why? I am now using jquery 1.9.1. My script worked previously when I was using jquery 1.8 with live() instead of on().

HTML:

<tr class="row">
    <td><input type="checkbox"></td>
</tr>

jquery:

$(document).ready(function(){
    $("body").on("click",".row",function(){
        var loc = $(this).find('input');
        var ischecked = loc.attr("checked");
        if(ischecked) {
            loc.attr("checked", false);
        } else {
            loc.attr("checked", true);
        }
    });
});
Nancy Collier
  • 1,469
  • 4
  • 17
  • 21
  • 5
    I think you should be using `loc.prop("checked")`, not `.attr()`. – Barmar Apr 04 '13 at 04:00
  • 1
    Setting "checked" attr to true or false has nothing to do with the checkbox being checked or not. As long as the attribute is there, it is checked. – Antony Apr 04 '13 at 04:01
  • You should add and remove the attribute, not set it to true orfalse. – box86rowh Apr 04 '13 at 04:02
  • 1
    As @Barmar says, use prop. See this SO question: http://stackoverflow.com/questions/426258/how-do-i-check-a-checkbox-with-jquery-or-javascript – Simon C Apr 04 '13 at 04:04
  • if(ischecked == "checked"), try with this condition – A.T. Apr 04 '13 at 04:05
  • @box86rowh - It's much better to use `prop` with checkboxes. This is [well documented](http://api.jquery.com/prop/). – jahroy Apr 04 '13 at 04:15

2 Answers2

1

You need to replace attr with prop as below

$(document).ready(function(){
    $("body").on("click",".row",function(){
        var loc = $(this).find('input');
        var ischecked = loc.attr("checked");
        if(ischecked) {
            loc.prop("checked", false);
        } else {
            loc.prop("checked", true);
        }
    });
});

jsfiddler

viclim
  • 959
  • 8
  • 16
0

When the checked attribute is there in an <input />, never mind about its value, it becomes checked. So replace the following:

loc.attr("checked", false);

With:

loc.prop("checked", false);

Or, you can do so in a single line of code this way:

loc.prop("checked", !loc.prop("checked"));
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252