Set click event to an element that was inserted via AJAX, after page loading

Asked

Viewed 70 times

3

I am developing an instant search system with jQuery, Ajax and PHP. I created a navigation system by the arrow keys of the keyboard in the options resulting from the search. It is working smoothly. But what I want to do is that when enter is keyboard on one of these search options, a click is triggered in the selected option. The problem is that these options are loaded after page loading. So I can’t set a click the traditional way with .click(), in that element.

I tried to use the

$(elementoPai).on('click', 'elementoFilho', function(){

});

But this only assigns a callback to when the 'elementoFilho' is clicked. And that’s not what I want. What I want is to set! Click! on this 'elementFile' by typing the enter.

Can someone help me ?

Thank you in advance.

  • You can post the code that makes the Ajax request?

  • I didn’t get it right. Have an example of HTML? when you click enter you want to fire a click on an element.

2 answers

2

click is with the mouse, touch finger, keydown with the keyboard... after all you can not click with the keyboard or type with the mouse.

$(elementoPai).on('click keydown', 'elementoFilho', function(event){
  if (event.type == "click" || event.which == 13) {
    // 13 -> Enter
  }
});

1

You have to link the element and the listern event to the document Document DOM. Try this function below, it will work for any DOM element created in the future:

//Vc enqueceu de escolher o selector => elementoFilho é uma classe ou um ID?
//Se for id
$(document).on("click keydown", "#elementoFilho", function(e){
    e.preventDefault();//Se quiser previnir o comportamento default. 
    //ponha seu cdigo aqui
}); 

//Se for class
$(document).on("click keydown", ".elementoFilho", function(e){
    e.preventDefault();//Se quiser previnir o comportamento default. 
    //ponha seu cdigo aqui
});  

Browser other questions tagged

You are not signed in. Login or sign up in order to post.