简体   繁体   中英

Setting checkbox as checked with jQuery

I have two input checkboxes, and I want to check/uncheck them with jQuery:

<input type="checkbox" name="user1" value="1" id="u1" onclick="loadUserCalendar(1)">
<input type="checkbox" name="user2" value="2" id="u2" onclick="loadUserCalendar(2)">

JavaScript code:

var list = new cookieList("calendar_users"); 
var users = list.items();
for (var i = 0; i < users.length; i++) {
    $('input[name="user' + users[i].substr(1,1) + '"]').attr('checked', true);
    console.log('substring: ' + users[i].substr(1,1));
    console.log('enabling user ' + users[i]);
}

var users contains these values: u1,u2 . To only get the user ID, I perform a substring, which gets me the correct number as you can see below in the console output.

Console output:

substring: 1
enabling user u1
substring: 2 
enabling user u2 

I have no idea, why the checkboxes are not checked when the code ran. What am I doing wrong here?

Edit : I am using jQuery 1.4.4 due to compatibility reasons, that's why I am using .attr()

Inline event handlers ( onclick="loadUserCalendar(1)" ) are not the jQuery way. You should not have any in your html. Get rid of them and add to your jquery:

$(function() {
    $('form').on('click',':checkbox', function() {
        loadUserCalendar($(this).val());
    });
});

But maybe what you wanted was this:

$(function() {
    $('form').on('click',':checkbox', function() {
        $('form :checkbox').attr('checked','checked');
    });
});

The jquery 1.ancient version:

$(function() {
    $('input[type=checkbox]').live('click', function() {
        // do things
    });
});

What version of jQuery are you using?

You have to try something like :

$('input[name="user' + users[i].substr(1,1) + '"]').attr('checked', 'checked');

or

$('input[name="user' + users[i].substr(1,1) + '"]').prop('checked', 'checked');

The second one is jQuery 1.6+

当您想要检查某些东西时,必须执行以下操作:

 $('.myCheckbox').attr('checked','checked');

如果创建了复选框,则动态使用jQuery on方法,因为简单的函数将无法访问这些元素。

Regarding the initialization of the checkboxes I would suggest something like this:

$('input[type=checkbox]').each(function(index, box) {
    $(box).attr('checked', $.inArray($(box).attr("id"), users) != -1);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM