Comment faire fonctionner le sélecteur de date pour les zones de texte créées dynamicment

J’ai un bouton ‘append’ qui crée des champs de texte dynamics. Les champs de texte de date de début et de date de fin par défaut affichent le sélecteur de date. Toutefois, les zones de texte créées dynamicment n’affiche pas le sélecteur de date. Toute aide serait appréciée.

$(document).ready(function() { $('input[name="settings[start_date][]"]').datepicker({ maxDate: constants.MAX_YEAR + '-12-31', changeYear: true, changeMonth: true, dateFormat: 'yy-mm-dd' }); $('input[name="settings[end_date][]"]').datepicker({ maxDate: constants.MAX_YEAR + '-12-31', changeYear: true, changeMonth: true, dateFormat: 'yy-mm-dd' }); $('#container').on('click', '.remove', function() { $(this).parent().remove(); }); $('#add').on('click', function() { var row = $('div.addNew:first').clone(); $('#container').append(row); }); }); 
 
Start Date : End Date :

Vous pouvez assez facilement append un datepicker aux éléments nouvellement créés

NB Dans cet exemple, j’ai pris la liberté d’append une classe “datepicker” à vos zones de texte afin de simplifier le code. Assurez-vous donc de modifier également votre code HTML. J’ai également réduit le nombre de répétitions dans votre code en transformant les options de datepicker en un object réutilisable:

HTML / PHP:

 
Start Date : End Date :

jQuery:

 //I have assumed this, just for the sake of an example: var constants = { MAX_YEAR: "2020" }; //re-usable set of options var datePickerOptions = { maxDate: constants.MAX_YEAR + '-12-31', changeYear: true, changeMonth: true, dateFormat: 'yy-mm-dd' }; $(document).ready(function() { //set datepicker on all existing elements with "datepicker" class $('.datepicker').datepicker(datePickerOptions); $('#container').on('click', '.remove', function() { $(this).parent().remove(); }); $('#add').on('click', function() { var row = $('div.addNew:first').clone(); $('#container').append(row); var pickers = row.find(".datepicker"); //find elements within the new row which have the "datepicker" class //since we cloned them, remove the "id" atsortingbutes and "hasDatepicker" class, both of which were added by jQueryUI, otherwise the datepicker will not initialise properly on these new elements pickers.removeAttr("id"); pickers.removeClass("hasDatepicker"); pickers.datepicker(datePickerOptions); //add a datepicker to each new element }); }); 

Vous pouvez également visiter http://jsfiddle.net/yqr69eca/17/ pour voir une démonstration de travail de ce code.

écris ta fonction comme ça

 $(document).on('click','#targetid',function(){ /*Do something logically here*/ // On a side note it will always work on dynamic,static elements });