Reputation: 11493
I'm dynamically adding new form elements using jquery. For some reason, a call to .datepicker()
won't work on the new elements I add, but did work on the old ones that were not added dynamically. If I put .attr('style', 'color: red;')
instead of .datepicker()
, it works. Note that the original call inside of the document ready function works.
This is the code that gets called when the add button is clicked:
function addMulti(name) {
it = $('[name=' + name + ']');
base = it.data('baseName');
on = it.data('number') + 1;
name = base + "-" + on;
copy = it.clone()
copy.prop("name", name).attr("data-is-default", false).removeAttr('data-number').
fadeIn('slow').appendTo(it.parent());
it.data('number', on);
if(it.hasClass('date-pickable')) { // <-- This returns true, I checked.
copy.datepicker();
// Where if I add clone.attr('style', 'color: red;') it turns it red.
}
}
This is the call that makes all of the fields that are created at that point date pickers:
<script type="text/javascript">
$(document).ready(function() {
$("input.date-pickable").datepicker()
});
</script>
There are no errors that show up in firebug or the google chrome "inspect element" thing. Something odd is happening though. If I type in the same call as in the document.ready function into the firebug consul, it still won't make the newly added elements datepickers. Yet if I hover over the output, it selects the elements that it should be targeting.
$("input.date-pickable").datepicker() // What I typed in
Object[input#dp1371953134342.field-input 06/22/2013, input#dp1371953134343.field-input, input#dp1371953134342.field-input 06/22/2013, input#dp1371953134342.field-input 06/22/2013] // What it put out. The last three numbers are the IDs JQuery assigned to the added elements. I checked.
Upvotes: 0
Views: 447
Reputation: 318302
jQuery UI's datepicker will always add the class hasDatepicker
to any element that has a datepicker to avoid attaching multiple datepickers to the same element.
When you're cloning an element that already has a datepicker, you get that class as well, and you can't attach a new datepicker to the clone, as jQuery UI thinks the element already has a datepicker.
Remove the class from the clone:
var copy = it.clone(false);
copy.removeClass('hasDatepicker').prop("name", name)
.attr("data-is-default", "false").removeAttr('data-number')
.fadeIn('slow').appendTo(it.parent());
and try not to make all your variables global.
Upvotes: 2
Reputation: 24468
Will this work?
<script type="text/javascript">
$(document).ready(function() {
$(document).on('focus',"input.date-pickable", function(){
$(this).datepicker();
});
});
</script>
Upvotes: 0