Jquery click label + checkbox determines what?

I am trying to check event.target.nodeName as follows:

$("input").click(function(e){ if(e.target.nodeName == "LABEL") { alert('label click'); e.preventDefault(); } else { alert($(this).attr('checked') ? 'checked': 'unchecked'); } }); 

But the name never matches the label? What am I doing wrong?

Fast jsfiddle

+4
source share
3 answers

You must select the label (parent) element. Currently, the sole purpose of your click handler is the input element:

 $("label").click(function(e){ // ... }) 

http://jsfiddle.net/j7nSq/

+5
source

I think the reason is that this does not work, because it will only work when clicking on the input:

  if(e.target.nodeName == "LABEL") { 
+2
source

You do not select a shortcut at all. First select the shortcut and try again:

You get into the wrong item here.

 $('label').on('click', function(e) { // Your logic here }); 

Instead of clicking on input.

Make sure you delegate the event using .on() .

+1
source

Source: https://habr.com/ru/post/1436016/


All Articles