4

I am trying to check the 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 equals label? What am I doing wrong?

Quick jsfiddle

2
  • 1
    In this scenario nodeName will always be equal to the element you selected for the event. There's no way to attach to the label unless you select the label initially. Commented Sep 24, 2012 at 21:46
  • 1
    Always bind the container element if you thinking of using e.target, basically the handler is executed as the event bubbled all the way down to the child element. Commented Sep 24, 2012 at 21:47

3 Answers 3

5

You should select the label(parent) element. Currently the only target of your click handler is the input element:

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

http://jsfiddle.net/j7nSq/

Sign up to request clarification or add additional context in comments.

Comments

2

I think the reason this doesn't work is because this will only run if you click on input:

  if(e.target.nodeName == "LABEL") {

Comments

1

You are not selecting the label at all. Select the label first and try again:

You are hitting the wrong element here..

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

});

Instead of click on input.

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

3 Comments

Nitpick: your example uses on(), but it's not delegating.
I'm not even sure I'm correct anymore (since your code does handle clicks bubbled from the input), but usually when I see the term "delegation" it refers to cases when you target descendant nodes, but the handler is attached to the parent (like in $('label').on('click', 'input', function ..., which wouldn't solve the OP problem here). So forget what I said, I'm not sure if that's technically delegation or not.
@bfavaretto.. Think I used the wrong workd here.. Looks like you are right :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.