Wednesday, March 16, 2011

Things To Know About Creating Multiple jQuery UI Datepicker Widgets on the Fly

The first time I created a UI where users could create new jQuery UI Datepicker widgets on the web page as needed, I thought about blogging about some of the "gotchas" I ran into trying to do that, but never got around to it.

But after today, when I had to relearn those lessons, I figured I should write something down.  :)

Here's what I've observed about creating new (multiple) Datepicker widgets on the fly:

  • Cloning a text field that already has the Datepicker applied to it won't work.  You're better off either cloning a "plain" text input element (<input type="text">) or creating one from scratch when you need it.

  • If there's any chance that you're going to end up with multiple Datepicker widgets on the page, you need to make sure that each Datepicker-powered text element ends up with a unique value in the "id" attribute.  Otherwise, the user will click on a date on the pop-up calendar for the most recently-added Datepicker widget, but it'll change the text box value of the first Datepicker widget you added!

    One way to address this is to add a global numeric variable at the top of your Javascript block, increment it every time you want to add a new Datepicker, and combine the current value of that variable with some text and assign that as the id of the text element you're about to add as a Datepicker.

  • Do not invoke the datepicker() function (the function that turns the text field into a Datepicker widget) on the new text input element until after it has been added to the page:  clone or create your text input first, place it in the page using prepend(), append(), whatever, and then invoke the datepicker() function on it.

  • If you need to remove one of the Datepicker widgets, use the datepicker("destroy") method on it.

No comments:

Post a Comment