0

I want to add an event handler to some dynamically added elements. I simplified my problem into the basic code below. I am using the new JQuery 1.7 on feature to say "hey for all labels in the CancelSurvey id element call this notify function when they are clicked."

function notify(event) {
    console.log(event.data.name);
}
$('#CancelSurvey').on('click', 'label', { name: $(this).attr("id") }, notify);

I want to pass the id of the label as parameter "name". When I try to alert this it is undefined (they are defined in the html created). I believe that using the $(this) is not referencing the label selector in this case. It actually seems to be referencing the document itself. Any ideas on how to accomplish this?

2 Answers 2

2

It's because you're evaluating this of the enclosing context where the handler is assigned, therefore it isn't a reference to the eleent.

Since you know the ID, you can use a string.

$('#CancelSurvey').on('click', 'label', { name: 'CancelSurvey' }, notify);

Or skip the event data, and just get it from the element in the handler

function notify(event) {
    console.log(this.id);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Trying to pass the id of the label clicked. Would like to do this weather or not I know the CancelSurvey. This case is a little simplified. An anonymous function is not appropriate for the full scope of what I am trying to do
@JBone: See the second half of my answer. You don't need to store it in the event object. Just use this.id in the handler. Doesn't matter if the function is anonymous or not. I'm using your notify function.
0

The DOM element that triggered the event should be passed into the click handler, you could pull the ID that way in the event handler. I'm pretty sure that in the handler, this points to the DOM element that triggered the event.

Comments

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.