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.
Add a comment
|
1 Answer
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.
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.
3 Comments
CodingIntrigue
+1. Or just write a more accurate selector -
$("button[id^='hotel']")DrColossos
Then he would also need delegation since the buttons are added after the DOM is loaded ;)
CodingIntrigue
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