I am populating a dynamic list using javascript. I have a onclick action where I need to get the clicked item from list. HTML is as:
<div class="cate-map">
<ul id="option1" onclick="doSelection()">
</ul>
</div>
I am populating list as:
jQuery.get(url, function(data) {
for(i=0;i<data.length;i++){
msg = "<li data-input="+data[i]+" class='selected'> <a href=#>"+data[i]+"</a></li>";
document.querySelector('#option1').innerHTML += msg;
}
});
Onclick Listener is as:
function doSelection(){
var id =$('#option1 li.selected').attr('data-input');
alert(id);
}
Problem is that whenever I click li I am still getting the first element of the list. Not the one I clicked. Please help.
I would recommend you to use Event Delegation using .on() delegated-events approach.
i.e.
$(document).on('event','selector',callback_function)
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the event binding call.
The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.
Example
$('#option1').on('click', 'li', function() {
var id = $(this).data('input');
alert(id);
});
$(document).ready(function() {
var data = [1, 2, 3];
for (var i = 0; i < data.length; i++) {
var msg = "<li data-input=" + data[i] + " class='selected'> <a href=#>" + data[i] + "</a></li>";
$('#option1').append(msg);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cate-map">
<ul id="option1">
</ul>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With