I’m building a web application, and for some time it has been bugging me, that when I load HTML into my page by ajax, I need to refresh my functions within $(document).ready().
Let’s for example say I have this:
$(document).ready(function () {
$('#searchInput').keyup(function () {
// Do something
});
});
However my input field with id=”searchInput” is not loaded when the DOM is loaded – it is being loaded later on using an ajax, when the user clicks a specific element.
Now my input field with id=”searchInput” is loaded, but the keyup(function) does not listen to #searchInput since it was not loaded in the original DOM.
For now, my only solution has been to do like this:
function loadEvents() {
$('#searchInput').keyup(function () {
// Do something
});
}
$(document).ready(function () {
loadEvents();
});
And then on ajax succes:
succes:
function() {
loadEvents();
}
This works… But I can’t help to think that there is a smarter way…
I have multiple functions within my loadEvents(), and for me I does not seem like the best solution to reload all functions every time an ajax call is successful?
Of course I could then make many different ajax calls, which on ajax succes executes specific functions needed, but then I will have to create many different ajax functions.
Any better solutions out there?
You can use the following code to consolidate all your success callback code in one place
See more about it at http://api.jquery.com/ajaxSuccess/