Reputation: 7315
My problem is really simple, i have a hidden checkbox and a custom fake checkbox which triggers the real one. I've tried lots of various methods but click
function works only at the begining than stops.
I've and searhed alike questions on stackoverflow but coun't find a problem which similar to mine. Thank you for your time.
html:
<div class="fl">
<span class="tri_checkbox"></span>
<input class="hidden_checkbox" type="checkbox" />
</div>
jQuery:
$(document).on('click','.tri_checkbox',function() {
if ( !$(this).hasClass('selected') ) {
$(this).parent().find('input.hidden_checkbox').attr('checked','checked');
$(this).addClass('selected');
}else{
$(this).parent().find('input.hidden_checkbox').removeAttr('checked');
$(this).removeClass('selected');
}
});
Upvotes: 0
Views: 113
Reputation: 10216
.
$(document).on('click','.tri_checkbox',function() {
if ( $(this).hasClass('selected') ) {
$(this).siblings('input.hidden_checkbox').prop('checked', false);
$(this).removeClass('selected');
}
else {
$(this).siblings('input.hidden_checkbox').prop('checked', 'checked');
$(this).addClass('selected');
}
});
Upvotes: 1
Reputation: 104775
Shorten your code up and try this:
$(this).toggleClass("selected");
$(this).parent(".fl").find(":checkbox").prop("checked", $(this).hasClass("selected"));
Demo: http://jsfiddle.net/CVWWn/4/
Or just use one big chain:
$(this).toggleClass("selected").parent(".fl").find(":checkbox").prop("checked", $(this).hasClass("selected"));
Big chain: http://jsfiddle.net/CVWWn/5/
Upvotes: 3
Reputation: 388316
You need to use .prop() to set the checked property
$(document).on('click', '.tri_checkbox', function () {
$(this).next().prop('checked', function (_, checked) {
return !checked;
});
$(this).toggleClass('selected');
});
Demo: Fiddle
Read: Attributes vs. Properties
Upvotes: 4