简体   繁体   中英

jQuery: Make div clickable to check nested checkbox

<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.

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.

<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>

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM