here is the trick:
$('body').on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});
DEMO
The $('...selector..').on('..event..', '...another-selector...', ...callback...);
syntax means:
Add a listener to ...selector..
(the body
in our example) for the event ..event..
('focus' in our example). For all the descendants of the matching nodes that matches the selector ...another-selector...
(.datepicker_recurring_start
in our example) , apply the event handler ...callback...
(the inline function in our example)
See http://api.jquery.com/on/ and especially the section about "delegated events"
For me below jquery worked:
changing "body" to document
$(document).on('focus',".datepicker_recurring_start", function(){
$(this).datepicker();
});
Thanks to skafandri
Note: make sure your id is different for each field
Excellent answer by skafandri +1
This is just updated to check for hasDatepicker class.
$('body').on('focus',".datepicker", function(){
if( $(this).hasClass('hasDatepicker') === false ) {
$(this).datepicker();
}
});
Make sure your element with the .date-picker
class does NOT already have a hasDatepicker
class. If it does, even an attempt to re-initialize with $myDatepicker.datepicker();
will fail! Instead you need to do...
$myDatepicker.removeClass('hasDatepicker').datepicker();
You need to run the .datepicker();
again after you've dynamically created the other textbox elements.
I would recommend doing so in the callback method of the call that is adding the elements to the DOM.
So lets say you're using the JQuery Load method to pull the elements from a source and load them into the DOM, you would do something like this:
$('#id_of_div_youre_dynamically_adding_to').load('ajax/get_textbox', function() {
$(".datepicker_recurring_start" ).datepicker();
});
The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to use ( _.each ) function.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {
_.each(repeaterWrapper, function (repeaterItem, index) {
var jq_nodes = $(repeaterItem.addedNodes);
jq_nodes.each(function () {
// Date Picker
$(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
dateFormat: "dd MM, yy",
showAnim: "slideDown",
changeMonth: true,
numberOfMonths: 1
});
});
});
});
observerjQueryPlugins.observe(document, {
childList: true,
subtree: true,
attributes: false,
characterData: false
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With