A. Rossi A. Rossi - 4 months ago 42
jQuery Question

check checkbox on click href and on click checkbox

I know there is many topics for check a checkbox by clicking on href, but in every solution i seen, you can't check the checkbox by clicking on the checkbox, because it wrapped by the

<a>
tag.

There is my html :

<a href='#' id='cb'>mode<input type='checkbox' id='mode'></a>


My Jquery :

$("#cb").click(function(e) {
e.preventDefault();
$("#mode").prop("checked", !$("#mode").prop("checked"));
})


What I need :

I need to be able to check the checkbox by clicking on href AND by clicking on the checkbox.

If this post is duplicate, i'm sorry but i didn't see it, link me the duplicate and i'll remove this.

JSFiddle

Answer

Check tag name of target to prevent while clicking on input - https://jsfiddle.net/fwzd08cw/2/

$("#cb").click(function(e) {
    if((e.target).tagName == 'INPUT') return true; 
    e.preventDefault();
    $("#mode").prop("checked", !$("#mode").prop("checked"));
});
Comments