Checkbox inside an anchor click behavior

霸气de小男生 提交于 2019-12-01 05:11:51

Well, it looks like a known Firefox bug, which leads to following link on checkbox click regardless of handlers' code. As a bit dirty workaround one can use:

var checkbox = $('<input type="checkbox"></input>');
checkbox.prependTo($('#a'));
checkbox.click(function(e) {
    setTimeout(function() { checkbox.prop('checked', !checkbox.prop('checked')); }, 10);       
    // do something useful on clicking checkbox and but not surrounding link
    return false;
});

I know this is an old question but some may still be curious since it was never really fully answered without a messy hack or workaround. All you have to do is simply check where the event's target originated.

So using your example (jsfiddle):

// Don't change pages if the user is just changing the checkbox
$("#a").click(function(e) {
    //e.preventDefault(); // Optional if you want to to keep the link from working normally

    alert("Click came from: " + e.target.tagName);
    if (e.target.tagName != "INPUT") {
        // do link
        alert("Doing link functionality");
    } else {
        // do something useful
        alert("Doing checkbox functionality");
    }
});

I Know this question is over 5 years old, but I had the same issue recently and the work-around I found was to add an onclick function to the checkbox and in that function call event.stopImmediatePropagation().

from w3schools: "The stopImmediatePropagation() method prevents other listeners of the same event from being called"

ie...the anchor.

function checkbox_onclick(event){
event.stopImmediatePropagation(); 
}

here's a modified script

var checkbox = $('<input type="checkbox"></input>');
var a = $('#a');
a.unbind("click").click(function(e) {
    e.preventDefault();
    checkbox.attr('checked', !checkbox.attr('checked'));
});
checkbox.prependTo(a);
checkbox.click(function(e) {
    e.stopPropagation();
    // do something useful 
});

i unbind the click event on the <a> and rebind it with a event to check/uncheck the checkbox and also prevent the default.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!