Reputation: 22050
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
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
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