Thursday, October 25, 2012

Adding a Time Selector to the jQuery UI Datepicker Widget

One of the functional requirements for the voter registration application I blogged about recently was that the application should not allow further registrations between the registration deadline (October 16 at 9pm) and a date after the election specified by the state Board of Elections.  For the initial run of the application, I simply hard-coded the deadline and restart date into the application logic, knowing full well I couldn't leave it that way unless I wanted to personally change the code year after year....which I don't.

So this week I set out to write a tool within the administrative interface of the application that would allow a non-programmer to update the deadline and restart date every year.  The jQuery UI Datepicker widget is my tool of choice when it comes to having users enter or edit a date, but I've used a few different approaches to having users enter a time of day.  This time around, I decided to see I if could find something comparable to the Datepicker widget for setting the time.

What I found was a rather sweet plugin called the Timepicker Addon that adds a set of time controls to the jQuery UI Datepicker.  If you customize your jQuery UI download to include both the Slider and Datepicker widgets, you can present the time controls as sliders, like so (without the Slider widget, you get select boxes):

The plugin comes with a number of configuration settings so you can do things like adjust the time increments, change how the time is displayed, and allow the user to denote the time zone associated with the time value.  Once I had the plugin configured the way I wanted, I simply had to write some code to validate the date and time string submitted from the form field, and I was done.  Very cool.

No comments:

Post a Comment