Override parrents onClick event with checkbox onClick?

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


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 } });


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


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


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

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:Override parrents onClick event with checkbox onClick?