9

This is similar to How to Display Selected Item in Bootstrap Button Dropdown Title

Only difference, my dropdown list is not static and it is populated through ajax response. Below code doesn't work only for <li> items which are populated dynamically.

To test above, I intentionally put a static <li> when I click on that item, I can see success message in console. But, when I click on <li> which are appended dynamically, I don't get anything in console.

I believe, there is some jQuery fundamental knowledge I missing here. jQuery gurus, comments/thoughts?

Here is some code for further clarification.

Java Script Code:

Printing selected option in console

$(".dropdown-menu li a").click(function () {
        console.log("Selected Option:"+$(this).text());
});

Populating dropdown from ajax JSON response

$.each(response, function (key, value) {
    $("#dropDownUL").append("<li> <a tabindex=\"-1\" href=\"#\" align=\"left\"> " + value + "</a> </li>");
})

HTML code:

<div class="dropdown btn">
    <div id="dropDownId" class="dropdown-toggle" id="dLabel" role="button" data-toggle="dropdown" data-target="#">
        Collections
        <b class="caret"></b>
    </div>           
    <ul id="dropDownUL"  class="dropdown-menu pull-left" role="menu" aria-labelledby="dLabel">
    <li><a tabindex="-1" href="#" align="left">Static test Option</a></li>
    </ul>


</div>

So, once again, if I click on Static test Option I can see message in console : Selected Option: Static test Option

But, when I click on Option2 Option 3 which is populated from ajax response, I don't see anything in console.

Let me know if something is not clear. I will try to explain further.

Community
  • 1
  • 1
Watt
  • 3,118
  • 14
  • 54
  • 85

1 Answers1

19
$(document).on('click', '.dropdown-menu li a', function () {
    console.log("Selected Option:"+$(this).text());
});

This is just simple event delegation...Elements that don't exist at page load must have the event delegated to a static parent element that does exist at page load.

We leverage jQuery's .on() to complete this.

  $(staticElement).on(event, dynamicElement, function(){ //etc });

Obligatory Edit

Please don't actually bind elements to the $(document) and instead choose the closest parent element that is static. This is for performance reasons.

Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110