Nancy Collier
Nancy Collier

Reputation: 1529

Why does jquery's on() only work once?

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);
        }
    });
});

Upvotes: 2

Views: 223

Answers (2)

viclim
viclim

Reputation: 959

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

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

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"));

Upvotes: 0

Related Questions