Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 793
Jax Teller Avatar asked Jul 12 '16 08:07

Jax Teller


1 Answers

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

$("#cb").click(function(e) {
  if((e.target).tagName == 'INPUT') return true; 
  e.preventDefault();
  $("#mode").prop("checked", !$("#mode").prop("checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' id='cb'>mode<input type='checkbox' id='mode'></a>
like image 151
Sojtin Avatar answered Nov 13 '22 05:11

Sojtin