supercoolville
supercoolville

Reputation: 9086

Override Jquery .click Event

I have this HTML:

<style>
div.icons {
    background-color:red;
    width:100px;
    height:100px;
    float:left; 
    margin-right:10px;
}
</style>

<div class="icons"><input type="checkbox" checked="checked" />Box 1</div>
<div class="icons"><input type="checkbox" checked="checked" />Box 2</div>
<div class="icons"><input type="checkbox" checked="checked" />Box 3</div>

And this JQuery...

<script>
$(document).ready(function() {
    $("div.icons").click(
        function(){
            if ($(this).children("input").is(":checked")) {
                $(this).css("background-color","yellow");
                $(this).children("input").attr('checked', false);
            } else {
                $(this).css("background-color","red");
                $(this).children("input").attr('checked', true);
            }
        }
    );

});
</script>

When I click on a div, jquery changes the background color of the div and unchecks the input inside of it. But when I click on an input checkbox inside of the div, it doesn't check the input box.

Is there a way to override the $("div.icons").click when the checkbox is clicked? Or is there a better way to do this?

Upvotes: 0

Views: 4925

Answers (3)

Leo
Leo

Reputation: 675

Here is another way to override the jQuery click event:

$('div').unbind('click').on('click', '.icons', function (event) {
    event.stopPropagation();
});

it worked for me.

Upvotes: 4

mrtsherman
mrtsherman

Reputation: 39872

I would do it something like this. I think the code is far simpler.

  1. Use classes to govern the display. You can toggle the class using jQuery's toggleClass function.
  2. Use jQuery's .trigger to initiate clicks on the input elements for each div
  3. Prevent propagation of clicked inputs from creating an infinite loop.

http://jsfiddle.net/4hLrF/

div.icons {
    background-color:red;
    width:100px;
    height:100px;
    float:left; 
    margin-right:10px;
}

div.checked {
     background: yellow;   
}

$('input').click( function(e) {
    $(this).parent().toggleClass('checked');
    e.stopPropagation();
});

$('div').click( function() {
    $(this).children('input').trigger('click');
});

Upvotes: 4

Jasper
Jasper

Reputation: 76003

Yeah if you add event.stopPropagation() to a click event handler for the check-box elements you can stop the click event from bubbling up the the check-box's parents:

$('.icons').children().on('click', function (event) {
    event.stopPropagation();
});

Upvotes: 4

Related Questions