I have the following simplified html:
<div class="foo" style="width:200px; height:200px;">
<input type="checkb开发者_C百科ox" />
</div>
<script type="text/javascript">
$('.foo').click(function(){$(this).find('input:checkbox')[0].click();});
</script>
Clicking the 200x200 div 'foo' works well, and raises the click event for the checkbox inside it.
However when I exactly click the checkbox itself, it fires its 'normal' event, plus the jquery bound event above, meaning the checkbox checks itself, then unchecks itself again.
Is there a tidy way to prevent this from happening?
How about this: instead of using a div, use a <label>
. It's more semantically correct, does exactly what you want, and requires no JavaScript.
Working example here: http://jsfiddle.net/LhSG9/1/
Events bubble. You would need test the e.target
that was clicked.
And if you're just trying to check/uncheck the box, you should set its checked
property.
$('.foo').click(function( e ){
if( e.target.tagName.toUpperCase() !== 'INPUT' ) {
var cbox = $(this).find('input:checkbox')[0];
cbox.checked = !cbox.checked;
}
});
EDIT: Fixed a couple mistakes.
Working demo: http://jsfiddle.net/LhSG9/
You need to stop the click on the checkbox so it does not bubble up to the div.
$('.foo input:checkbox').click(function(e){
// will stop event from "bubbling"
e.stopPropagation()
})
It happens because when you click on the checkbox you are also clicking on the div because the checkbox is inside it. So what you should do is capture when the user clicks the inside the div but no the checkbox. If the user does click on the checkbox it will act with its default behavior checking/unchecking
$('.foo:not(':checkbox')').click(function(){
$(this).find('input:checkbox')[0].click();
});
include the following function in yiur $(document).ready function
-
give an id say test to your checkbox then -
$('#test').click(function(){
return false;
});
精彩评论