0

I'm trying to get the text from tag <a> in element <li> but it doesn't work.

for (i = 0; i < result.length; i++) {
  $("#ftrBtn-menu_Facility").append("<li id='ftrBtn-menu_Facility_" + (i) + "'><a href='#'>" + result[i].facility + "</a></li>");
  $("#ftrBtn-menu_Facility_" + (i)).click(function(){
    var text = $("#ftrBtn-menu_Facility_" + (i)).find("a:first").text();
    alert(text);
  });
}
mplungjan
  • 169,008
  • 28
  • 173
  • 236
PoorChristmas
  • 55
  • 1
  • 2
  • 9
  • Short answer: Just use `var text = $(this).find("a:first").text()` indide your click – Jamiec Dec 13 '17 at 15:33
  • This is a prime example of why you shouldn't use auto-generated `id` attributes. You could use a closure, or just `var text = $(this).find("a:first").text();`. – Rory McCrossan Dec 13 '17 at 15:33

1 Answers1

1

Why you dont just use class instead of using id ?
Here's my proposed solution

var result = [{
  id: 1,
  facility: 'test1'
}, {
  id: 2,
  facility: 'test2'
}, {
  id: 3,
  facility: 'test3'
}]
for (i = 0; i < result.length; i++) {
  $("#ftrBtn-menu_Facility").append("<li class='dtrBtn' id='ftrBtn-menu_Facility_" + (i) + "'><a href='#'>" + result[i].facility + "</a></li>");

}
$(".dtrBtn").click(function() {
  var text = $(this).text();
  alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="ftrBtn-menu_Facility"></div>
Neji Soltani
  • 1,522
  • 4
  • 22
  • 41