简体   繁体   中英

jQuery click event / event bubbling issues when trying to highlight an element & check a checkbox at the same time

Please have a look at this fiddle: http://jsfiddle.net/mrmartineau/53fkV/embedded/result/

The intended outcome is that when a .poll_option td is clicked, the background colour changes to pink & the checkbox is checked. Each option has different bugs, these are:

Option 1: The problem I have is that on Option 1, when I click the checkbox itself, it does not check but everything else works fine. By that I mean that when I click the label & the <td> the outcome is correct. It seems that the event is not bubbling correctly..

Option 2: For this one, I tried another solution (removed the .toggle() method) and tried to figure out what element is actually being clicked ( console.log(e.target.nodeName); ) and now I can click the checkbox but not the label, rather the label does not make the event work.

Could you please have a look at my code & see where I'm going wrong because I'm sure it can't be this hard...

Cheers

Proposed simpler solution:

$('.poll_option.one td').click(function (e) {
    $(this).toggleClass('highlight');
    $(this).find('input').prop("checked", $(this).hasClass("highlight"));
    console.log(e.target.nodeName);

// weird that clicking the label does not naturally propagate
// the click event to the parent
}).find("label").click(function () {
    $(this).closest("td").click();                
});

Demo.

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