views:

848

answers:

3
<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $('#myDiv').click(function() {
            var checkBox = $(this).children("input[type='checkbox']");
            checkBox.attr('checked', !checkBox.attr('checked'))
        });
    });
</script>

<div id="myDiv" style="background-color:red;height:50px;width:50px;">
    <input type="checkbox" />
</div>

I'm having problems making the div clickable so that it checks the nested checkbox. I would like to make it so this function works only if the mouse is not hovering the checkbox. How can I do this? Something like this:

if (!checkBox.isHover)
    checkBox.attr('checked', !checkBox.attr('checked'))

Note this question has been asked here before, but the answers did not seem to solve the problem. The wrapped label solution does not work properly in FireFox. Thank you.

+2  A: 

Try this:

$('#myDiv').click(function(evt) {
  if (evt.target.type !== 'checkbox') {
    var $checkbox = $(":checkbox", this);
    $checkbox.attr('checked', !$checkbox.attr('checked'));
    evt.stopPropagation();
    return false;
  }
});

Untested, but I just successfully used something along these lines on a project.

Luke Bennett
Works great and fastest gun, thank you.
+1  A: 
<script language="javascript" type="text/javascript">
    $(document).ready(function() {
        $('#myDiv').click(function(e) {
            e.stopPropagation();
            var checkBox = $(this).children("input[type='checkbox']");
            checkBox.attr('checked', !checkBox.attr('checked'))
        });
    });
</script>
KyleFarris
A: 

The issue is that if you actually click on the checkbox it will still trigger the click event on the div - event bubbling. You can add a click event to the checkbox which stops the bubbling, this way only the div binds to the event.

eulerfx