I have a ul element that gets populated with li elements via AJAX. Then I need to do something when clicking on those li elements. The funny thing is that it works the second time I click on the li element it but not the first time.
I've read every possible related question I could find on StackOverflow but I can't find the answer to my problem.
Here is an example of the AJAX code:
$('#university').on('keyup', function(){
$.ajax({
url: ajaxUrl,
data: {
"search": searchVal,
"action": 'autoComplete',
},
type: "POST",
dataType: 'json',
success: function(data) {
$(".univers-name-list").html("");
var dataItem=[];
dataItem=data.data.items;
if(dataItem){
dataItem.forEach(function(element,key) {
$(".univers-name-list").append('<li>'+element.name+'</li>')
});
}
}
});
});
And here is the on click function (in the same file):
$('.univers-name-list').on('click', 'li', function(e){
// Code here
console.log('Helo'); // Doesn't run the first time.
});
Any idea what I'm doing wrong? Why does it only work when I click it for the second time?
Some more info: When I checked the event target, the first time I click on any li element, the target is UL (populated with the dynamically added LI elements), but the second time is the correct LI element.