I have a parent div which hold a check box what i would like to achieve is check or uncheck the wherever I click in the parent div or directly on the check box.
$('.select').click(function(){
var checkbox = $(this).find('input[type=checkbox]')
if (checkbox.is(':checked')){
checkbox.prop('checked', false);
}else{
checkbox.prop('checked', true);
}
});
http://jsfiddle.net/halirgb/Lt2Hw/2/
The problem is that if you click directly on the check box it dos not check :(
Can anyone help?
It is because event propagation.
When you click on the checkbox first the checkbox changes its state, then the event is propagated to the the parent elements thus reaching the .select
element where the state is again reversed to so it gets back to the state before the click
Try
$('.select').click(function (e) {
var checkbox = $(this).find('input[type=checkbox]')
if (checkbox.is(e.target)) {
return;
}
checkbox.prop('checked', function (i, checked) {
return !checked;
});
});
Demo: Fiddle
Or prevent the propagation of the click event from the checkbox
$('.select').click(function (e) {
var checkbox = $(this).find('input[type=checkbox]')
checkbox.prop('checked', function (i, checked) {
return !checked;
});
});
$('.select input[type=checkbox]').click(function (e) {
e.stopPropagation();
});
Demo: Fiddle
Stop Propagation on Checkbox click event.
$('.select input[type=checkbox]').click(function (e) {
e.stopPropagation();
});
When you click on checkbox the parent is also clicked so event fires when changes it's state again .
Check this demo to understand the problem
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.