Reputation: 4189
I have a block of dynamic code which look like this.
var li3 = document.createElement('li');
li3.classList.add("col-sm-3");
li3.classList.add("no_padding");
var inner = "";
inner = inner + "<div class='dropdown'>";
inner = inner + "<button class='btn btn-default dropdown-toggle col-sm-12' style='border-radius: 0 4px 4px 0;' type='button' id='dropdownMenu1' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true' data-questnrid='"+questnrid+"' data-questionid='"+questionid+"' data-dlnkid='"+dlnkid+"' data-lnkid='"+lnkid+"' data-qstaskedid='"+qstaskedid+"' data-qstaskedgrpid='"+qstaskedgrpid+"'>";
inner = inner + "<span class='dropdown_text'>Choose a option</span>";
inner = inner + "<span class='caret'></span>";
inner = inner + "</button>";
inner = inner + "<ul class='dropdown-menu' aria-labelledby='dropdownMenu1'>";
inner = inner + "<li><a href='#' class='list-item'>Yes</a></li>";
inner = inner + "<li><a href='#' class='list-item'>No</a></li>";
inner = inner + "<li><a href='#' class='list-item'></a></li>";
inner = inner + "</ul>";
inner = inner + "</div>";
li3.innerHTML = inner;
document.getElementById(thisID).appendChild(li3);
in the web it looks more like this.
<li class='col-sm-2 no_padding'>
<div class='dropdown'>
<button class='btn btn-default dropdown-toggle col-sm-12' style='border-radius: 0px 4px 4px 0px; type='button' id='dropdownMenu1' data-toggle='dropdown' aria-haspopup='true' aria-expanded='true'>
<span class='dropdown_text'>Choose a option</span>
<span class='caret'></span>
</button
<ul class='dropdown-menu' aria-labelledby='dropdownMenu1'>
<li><a href='#' class='list-item'>Yes</a></li>
<li><a href='#' class='list-item'>No</a></li>
<li><a href='#' class='list-item'></a></li>
</ul>
</div>
</li>
The first block gets called by n button press and it generates the list perfectly.
But now I click on the dropdown to accept the value for that dropdown, and no event fires. This is what I used.
$('.dropdown-menu li > a').on("click", function(event){
console.log("fire");
$(this).closest('.dropdown').find('button span.dropdown_text').text(this.innerHTML);
});
This event fires for the first block of code which is not dynamically created. But any oter block added after that dont fire the event trigger.
Any ideas?
Oh and here is my libraries that I use, if that might cause something
<script type="text/javascript" src="media/js/jquery-3.1.1.min.js"></script>
<link rel="stylesheet" href="media/css/bootstrap.css">
<script type="text/javascript" src="media/js/bootstrap.js"></script>
Upvotes: 0
Views: 64
Reputation: 137
Try to select the entire document, and select your element after the "click" parameter.
$(document).on("click", ".dropdown-menu li > a", function(event){
console.log("fire");
});
Upvotes: 1
Reputation: 2642
$("body").on("click", '.dropdown-menu li > a', function(event) {
})
Because the element didn't exist when the script ran, the event listener is not added to the button.
Upvotes: 1