5

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

1
  • How about this guys : var apchk = '<input type=checkbox checked="checked" id="chkb">'; $('#c').html(apchk); Commented Oct 1, 2010 at 8:50

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

2 Comments

+1 ^_^ one comment though. Although jQuery helps you a lot, don't abuse it. chkb[0].checked is faster than chkb.is(':checked'). cheers!
yeah and a down-vote won't help. ;) Just some explanation and all of us are happy. ;)
1

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

18 Comments

You can check a checkbox with the keyboard, too.
ahh... so better to use .change() then. ;)
What about this var apchk = '<input type=checkbox checked="checked" id="chkb">'; $('#c').html(apchk);
@Jean - Why? what's with that?
@Jean - about .toggle() on checkbox, read this
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.