Checkbox not checked when using jquery toggle

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

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

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

}, 
function () {

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

});

HTML

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

How to do it.

Thanks jean

+5
source share
2 answers

Do you really need checkedit in code? (Is there something I missed?) When he clicked, he already switched his validation attribute value.)

The best way to do this is to use such changes,

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

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

Caching selectors in variables speeds up the work - no need to search in dom every time. Entering chkba variable means that it can be used elsewhere in your jQuery, instead of being used this.

+2

All Articles