Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading HTML into <div> with jQuery-ajax

I ran into a bit of trouble while trying to load an external HTML page into a div using jQuery-ajax. I had this div: <div id="content"></div> and wanted to fill it with $("#content").load("include/add.html"); It loads the HTML file perfectly, but inside that add.html is a button that should load add2.html(also using .load), but it seems that neither the button nor the datepicker in that file work. I'm guessing the .load function is responsible for that?

This is the content of add2.html:

<p>Nr: <input type="text"></input></p>
<p>Name: <input type="text"></input></p>
<p>Date: <input type="text" id="datepicker"></input></p>
<a href="#" id="button1">Next</a>

Please help, I'm desperate :D

like image 722
ehehhh Avatar asked Mar 29 '10 12:03

ehehhh


1 Answers

As the file is included to the page after the events are bound, the events do not apply to the elements in 'add.html'. You need to bind the events again or use .on() method. In the case of the datepicker, it's easier to go with the first approach:

$("#content").load("include/add.html", function() {
    // Apply datepicker to elements in 'add.html'
    $('#content .date').datepicker();
});

For the button in add.html, you can use delegation:

$(document).on('click', '#content .button_in_add', function() {
    alert("I work even when included dynamically!");
    $('#content').load('include/add2.html');
});

Note that .on() bins does not go inside the .load() callback as the datepicker part did. If you have any elements in 'add2.html', you need to repeat the same steps for that also.

like image 160
Tatu Ulmanen Avatar answered Sep 21 '22 23:09

Tatu Ulmanen