开发者

Checkbox not getting checked when using jquery toggle

开发者 https://www.devze.com 2023-01-18 03:23 出处:网络
I want the checkbox to be checked when I am using jquery toggle function.It works fine when I use the .bind(\'click\').

I want the checkbox to be checked when I am using jquery toggle function. It works fine when I use the .bind('click').

$('#chkb').toggle(function () {

    $('#va').text("checked");
    $('#chkb').attr('checked', 'checked');

}, 
function () {

    $('#chkb').attr('开发者_如何学Gochecked', 'false');
    $('#va').text("");

});

html

<input type="checkbox" id="chkb" />

How do I get it done.

Thanks Jean


chkb = $('#chkb');
va = $('#va');

chkb.change(function () {
   va.text(chkb[0].checked ? "checked" : "");
});

Caching selectors into variables speeds things up - doesn't have to search the dom each time. Putting chkb into a variable means it can be used elsewhere in your jQuery, instead of using this.


do you really have to checked it in code? (Is there something I missed? checkbox when clicked, already toggle it's checked attribute value.)

Better way to do this is by using change like this,

$('#chkb').change(function () {
    var self = this;
    $('#va').text(function(i,text){
        return self.checked?"checked":"";
    });
})
0

精彩评论

暂无评论...
验证码 换一张
取 消