I have an ajax function that will get respond from server the respond will contain some buttons, I want to control them with jQuery, but the problem is that they won't exist once the page is opened so I can't control them with $(document).ready(function()
Is there any other way to do this ?
Have you tried event delegation?
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future
https://learn.jquery.com/events/event-delegation/
You just need an empty wrapper element where you will render the buttons in the future, after page loads. So, when you add the buttons, you will be able to interact with them.
At the beginning, the wrapper element must exists in your HTML:
<div id="buttonsWrapper"></div>
After that, after the ajax call is completed, then you append the buttons from the server to that element:
<div id="buttonsWrapper">
<button>From server</buttom>
<button>From server</buttom>
</div>
With this JS, you delegate the click event on the wrapper "#buttonsWrapper" element:
$(function(){
$("#buttonsWrapper").on( "click", "button", function( event ) {
event.preventDefault();
console.log( $( this ).text() );
});
}());
With event delegation, it doesn't matter if you add the buttons after page loads. Hope that helps!
Make prepare function in document and when the buttons load run it!
<script>
function loadOK()
{
// put your document ready codes here
}
$.post("your.url.address.for.get.buttons",data)
.done(function(data){ loadOK(); })
.error(function(){ alert("ajax cant complate";)});
</script>
after your buttons added call this function.