3
votes

I have the following jQuery script defined on all my forms.

$( "input:text.datepicker" ).datepicker({ 
    yearRange: "1900:+0",
    changeMonth: true,
    changeYear: true
});

Basically this invokes the date picker on any input element that is of type text and has the class "datepicker".

This works fine on all pages, except in one situation which I describe below.

I have to load a form by ajax, which is then displayed in a jQueryUI Dialog. In this dialog I can only get the date picker to display if I include the java-script code again. Obviously I don't want to include the code twice. Is there a way to get the newly loaded textbox to display the date picker somehow?

Thank you

2

2 Answers

11
votes

One option is to use on method in deprecated live way and click event to initialize Datepicker:

$('body').on('click', 'input.datepicker', function(event) {
    $(this).datepicker({
        showOn: 'focus',
        yearRange: '1900:+0',
        changeMonth: true,
        changeYear: true
    }).focus();
});

This code should be placed in $(document).ready section.

Pay attention to showOn: 'focus' option and triggering focus event after initialization.

DEMO: http://jsfiddle.net/Mq93s/

2
votes

Well the problem here is that when the datepicker code is executed, your form element does not exist yet, and therefore, it cannot convert it to a datepicker. You could bypass this problem by either:

  1. Moving the datepicker code to a separate function that you will then call manually from all pages in the document.ready event. This way it will only be declared once, and you can also call it in your ajax page as well, only there you will call it when the ajax call is completed instead of the ready event.
  2. Since you know what you're loading in your form, you can convert just that given input to a datepicker. This is not such a clean solution, because if you will want to change something in the datepicker, you'll have two places to modify, at least.

Both approaches are valid, the choice is up to you, as you know which version fits your project better :)