JQuery - add functionality to an element after loading ()

I have some code that loads some html from another file that works as it should. But I'm trying to access elements from this recently loaded data.

I have this code:

var widgetSettings = $("<div>").addClass("widgetsettings").load('dashboard/chart-settings-form.php #editChartForm'); widgetSettings.appendTo(widget.element); //so far so good... widget.element.find('.date').each(function(i){ $(this).datetimepicker(); //this doesn't work console.log('testing... '+$(this).attr('id')); //this doesn't even work... }); 

I expect him to find these text fields in the form of "#editChartForm" downloaded from the above URL (they are in the table):

 <input type="text" name="datefrom" id="datefrom" class="date" /> To: <input type="text" name="dateto" id="dateto" class="date" /> 

html is definitely loading. It's just very vague why I cannot access any elements from the load () event.

I also wanted to apply the click function to the cancel button in the same form, and I found that the only way to make it work is to put it in a β€œlive” function before loading:

 $('.cancel').live('click', function() { //actions here... }); 

Any ideas what is going on?

+4
source share
2 answers

Simple! Since the load () method is asynchronous, and your widget.element.find('.date') run before there are actually any elements in the DOM that match this! Just use the callback in your load (), for example:

 $("<div>").addClass("widgetsettings").load('dashboard/chart-settings-form.php #editChartForm', function() { $('div.widgetsettings').find('.date').each(function(i){ $(this).datetimepicker(); console.log('testing... '+$(this).attr('id')); }); }); 
+6
source
 $("div").load("url here",function(){ callbacks(); }); function callbacks(){ //put everything that you want to run after the load in here. //also if the click function is in here it wont need the .live call } 

Edit: Also with the latest jQuery version you can now use .on instead of .live (this is much more efficient), i.e.

 $(".widgetsettings").on("click",".cancel",function(){ //actions here }); 

hope this helps :)

+2
source

Source: https://habr.com/ru/post/1343199/


All Articles