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.