1

I have the following HTML.

<div id="programsData">
    <ul id="programsDataItems">
    </ul>
</div>

I populate the list using jQuery with this code snippet. Let's say it appends the list items (Item1 and Item2) to the list.

$.each(data, function (i, val) {
    $("#programsDataItems").append("<li><a href='#'>" + val.Value + "</a></li>");
})

Here is my function to get the list item clicked on:

$("#programsDataItems").click(function (e) {
    var selectedLi = $(this).text;
    e.preventDefault();
});

When I click on a list item, the above function returns: Item1Item2. I need to get only one list item. Can someone tell me how to get just the one list item clicked on? Do I need to modify how I am loading the list items?

Wannabe
  • 596
  • 1
  • 8
  • 22

2 Answers2

0

Replace

$("#programsDataItems").click(function (e) {

with

$("#programsDataItems").on("click", "li", function (e) {

This way you'll get the right context (this) in the callback, and the delegation will ensure you can still dynamically add LI elements to #programsDataItems after the binding.

Note that you should not add a A element in the LI element if the purpose is only to change the cursor. For that you can simply set cursor:pointer in CSS.

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • This works. Thanks. I will also look at removing the A element, per your suggestion. Thanks for looking further and explaining things. – Wannabe Jul 23 '15 at 14:56
0

You are assigning the event to the list, instead to the specific item in the list. Try

$("#programsDataItems li").click(function (e) {
    var selectedLi = $(this).text;
    e.preventDefault();
});
Igniz
  • 194
  • 1
  • 5
  • This won't work if the LI elements are added dynamically after the binding. – Denys Séguret Jul 23 '15 at 14:50
  • You're right, I was thinking he was adding the LI elements just once. Also I posted almost as the same time as you, and of course your answer is more suitable. – Igniz Jul 23 '15 at 15:29