Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

click event being fired twice - jquery

Tags:

html

jquery

input

I have the following simplified html:

<div class="foo" style="width:200px; height:200px;">
  <input type="checkbox" />
</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?

like image 330
maxp Avatar asked Jan 10 '11 17:01

maxp


2 Answers

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/

like image 172
Phrogz Avatar answered Oct 10 '22 03:10

Phrogz


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/

like image 29
user113716 Avatar answered Oct 10 '22 01:10

user113716