X10nD
X10nD

Reputation: 22050

Checkbox not getting checked when using jquery toggle

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('checked', 'false');
    $('#va').text("");

});

html

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

How do I get it done.

Thanks Jean

Upvotes: 5

Views: 1320

Answers (2)

NimChimpsky
NimChimpsky

Reputation: 47300

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.

Upvotes: 2

Reigel Gallarde
Reigel Gallarde

Reputation: 65274

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

Upvotes: 1

Related Questions