JackH
JackH

Reputation: 4735

How do I initialize a jQuery datepicker on a dynamically inserted <input> tag?

I have a form as follows:

<form id="my-form"></form>

I am using jQuery to dynamically insert an element into that form and then trying to initialize the Pikaday datepicker on the newly inserted input tag like this:

$('#my-form').html('<input type="text" id="datepicker">');
var departurePicker1 = new Pikaday({
    field   : $('#datepicker')[0],
    format  : 'MMM D',
    minDate : moment().toDate()
});

I am able to initialize the datepicker if the input tag was available on document load. However, the nature of my app is such that the input tag gets inserted into the DOM after a user interaction. How can initialize pikaday on this dynamically inserted DOM element? Please note that I CANNOT leave this element inserted in a hidden state since it involves user interaction. It has to be initialized when the user presses a button and the input tag gets inserted into the DOM.

Upvotes: 1

Views: 813

Answers (1)

Matthew
Matthew

Reputation: 817

Try this. You have to bind the event handler to the body using the on method.

$('body').on('focus',"#datepicker", function(){
    $(this).datepicker();
});​

Upvotes: 1

Related Questions