2

This is my code http://jsfiddle.net/amolw/6kdHG/
The buttons are created dynamically (usually the data for buttons will come through AJAX request). For simplicity I've hard coded those values.
My problem is when i execute this thisHotel = $(this).data('hname'); I get undefined in the variable thisHotel.
Same thing happens if i replace the buttons with anchor tag.

1 Answer 1

6

this in your example is the div id=hotels. It would have worked if you would have gone INTO the div and selected the button. I propose another solution though.

http://jsfiddle.net/6kdHG/3/

You can use the target of the event to get the information you want.

$("[id^='hotel']").on('click', function (e) {
    thisHotel = $(e.target).data('hname');
    $("#selected").html("Selected Hotel " + thisHotel);
});

e is the event that got triggered and you simply access it's target.

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

3 Comments

+1. Or just write a more accurate selector - $("button[id^='hotel']")
Then he would also need delegation since the buttons are added after the DOM is loaded ;)
Also a good point, but in your solution if I click between the buttons the .data() still returns undefined because I clicked on the div, but still not on a button

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.