0

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.

jstneti
  • 1
  • 3
  • I think we need more detail here, in particular the contents of your click handler function. – Robin Zigmond Jan 10 '19 at 09:51
  • even a console.log('helo') doesn't execute inside the click handler function. – jstneti Jan 10 '19 at 12:36
  • https://jsbin.com/ficofanafi/1/edit?js,console,output — I can't reproduce the problem. – Quentin Jan 10 '19 at 13:51
  • That's interesting. This snippet works. But not with real ajax. Any idea? – jstneti Jan 10 '19 at 19:23
  • @Quentin I've tried your snippet in the document ready and it worked. But as soon as I put it inside an on keyup callback it doesn't work. And that's what is actually firing up the ajax.I'll refresh my code. – jstneti Jan 11 '19 at 08:55
  • @jstneti — You need to provide a [mcve]. Maybe this is just a duplicate of [this](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element). Maybe you aren't triggering the keyup event correctly. – Quentin Jan 11 '19 at 09:07
  • @Quentin I was just trying to provide an example and it looks like it might be CSS related. By putting it outside of all the wrappers it's actually working ok. When I find the solution, I'll post it here in case it helps anyone else. Thanks for all the help and your time Quentin. – jstneti Jan 11 '19 at 09:30
  • It's not CSS, it's JS. A custom jquery validation rule on the input field that I somehow missed yesterday. – jstneti Jan 11 '19 at 09:36

3 Answers3

0

It was a custom validation rule on the input field that messed up everything. After fixing that rule, it now works as expected.

jstneti
  • 1
  • 3
-1

Event listeners will not work fFor elements created dynamically via javascript.

You have to use delegate functions for these kind of elements

This code should work fine on you element created dynamically.

$(document).on('click', '.univers-name-list li', function(e){
    // Code here
    console.log('Helo');
});
Gaurav Aggarwal
  • 8,921
  • 5
  • 27
  • 65
  • 1
    That is, more or less, what they are doing already. They're just binding to `.univers-name-list` (which is in the document) and not `document`. – Quentin Jan 10 '19 at 13:47
-1

You have to call addEventListener to the new created elements. check this Attach event to dynamic elements in javascript

JessGabriel
  • 917
  • 6
  • 14