2

First, sorry for my bad English.

I'm making a Coupons site and have trouble with selecting and deselecting the coupons. Each coupon is in a DIV 'box' in which there is a checkbox.

I made a onClick function on the DIV box (so the user can select the coupon by clicking on anything inside the DIV box. What I need now is, when the user want to deselect the coupon (by clicking on the checkbox inside the DIV box), I need to 'override' the DIV's onClick function (execute the checkbox onClick event, not the DIV's onClick event).

I know that everyone prefers some code as an example, but the question/problem is simple and I don't think you need all of my un'useless code inside the events/functions :)

Thanks :)

AlenBer
  • 738
  • 2
  • 8
  • 25
  • 2
    Code samples almost always make helping easier. That being said, have you looked into using jQuery's stopPropagation on the checkboxes? http://api.jquery.com/event.stopPropagation/ – j08691 Jan 14 '12 at 22:40

4 Answers4

3

It seems like you want stopPropagation if the checkbox is being unchecked: http://jsfiddle.net/8Dcq8/.

$("div").click(function() {
    alert("add"); // clicking anywhere in div to add coupon
});

$(":checkbox").click(function(e) {
    if(!this.checked) { // if unchecking, remove coupon
        alert("remove");
        e.stopPropagation(); // don't run parent onclick
    }
});
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • 1
    Ugh, no. `$(this).is(":checked")` is completely excessive. [All you need is `this.checked`](http://stackoverflow.com/a/4652402/139010). – Matt Ball Jan 14 '12 at 22:43
1

If the <div> click handler looks something like this:

var $boxes = $('div.box');
$boxes.on('click', function ()
{
    // do whatever to select the coupon
});

Then the checkbox handler should look something like this:

$boxes.find('input[type="checkbox"]').on('click', function (event)
{
    event.stopPropagation();
    // do whatever to deselect the coupon
});

See event.stopPropagation().

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
0

You have to cancel bubbling. See here for an explanation.

Milad Naseri
  • 4,053
  • 1
  • 27
  • 39
0

You can use the jQuery Alternative, or create sub-elements with onClicks that don't target your checkbox. you might be able to use something like this also.

document.getElementById('element').checked.onreadystatechange=function(){
//code

}

good luck

Adam Fowler
  • 1,750
  • 1
  • 17
  • 18