Reputation: 13881
I've got a form to which I add new date field elements using jquery/javascript on the fly. I'm trying to attach jquery's datepicker to that date field input( any widget/action would have the same behavior).
<script>
$(function() {
$( ".datepicker" ).datepicker();
});
</script>
<p>Date: <input type="text" class="datepicker"></p>
If an element is present in the original html of page, then the datepicker widget gets binded to date field. However, if the same date field gets added on the fly, the datepicker widget does not work. For clicking etc, jquery provides 'live' function, which can attach an action "after" an object gets created. But how can I mimic the same behavior for datepicker, so that it gets attached "after" object creation?
Upvotes: 0
Views: 1815
Reputation: 339786
If you're adding the element on the fly, just call .datepicker()
on it on the fly too!
Surely you must know at the time you create them that they're going to be date editing fields, so it should be trivial to directly enable the widget at the same time, e.g.:
var field = $('<input type="text" class="datepicker">').appendTo(page);
$(field).datepicker();
i.e, just use the selector for the element you just created and call .datepicker()
in the same way you did in your $(document).ready()
function for the pre-created elements.
I put a working demo at http://jsfiddle.net/sDHzG/ .
Note that the new elements don't have to have a specific class (unless you want that for other reasons) - the call to .datepicker()
can use the DOM element (per my example).
Upvotes: 3
Reputation: 6032
When your element gets added to the page, you could raise an event, and bind that event using jQuery live.
$(document).ready(function {
$("#form").live("datePickerCreated", function() {
$(this).datepicker();
});
});
function CreateDatePicker(id) {
datepickercode = '<p>Date: <input type="text" class="datepicker"></p>';
jQuery("#form")
.append(datepickercode)
.trigger("datePickerCreated");
}
Upvotes: 0
Reputation: 82325
It sounds like you want something like the Live Query plugin, it can match new elements based on a selector and execute code as you wish.
$(".datepicker").liveQuery(function() {
$(this).datepicker();
});
Upvotes: 2