Quick Tip: Create Cross-Browser Datepickers in Minutes
videos

Quick Tip: Create Cross-Browser Datepickers in Minutes

Tutorial Details
    • Topic - jQuery UI
    • Difficulty - Intermediate
    • Format - Video

In this quick tip, I’ll show you how to use the new HTML5 date input, and then provide a fallback jQuery UI solution for the browsers which don’t yet support this new input type.


Prefer a Video Tutorial?

Subscribe to our YouTube and Blip.tv channels to watch more screencasts.

Written Tutorial

We’ve all been there. You’ve created a form, and now you need the user to enter a date. But how do you control what format they enter the date in? Wouldn’t it be easier if we could use a calendar control, or a datepicker? Absolutely! Unfortunately, though, only a couple browsers support the new HTML5 date input type. That’s okay though, we’ll use jQuery UI to provide a fallback!


Step 1 – The Native Solution

Let’s first plan for the future, and assume that the user is working in a modern browser that supports a datepicker.


<!DOCTYPE html>

<html lang="en">
<head>
   <meta charset="utf-8">
   <title>Date Picker</title>

</head>
<body>

<input type="date" name="date" id="date" value="" />

</body>
</html>

At the time of this writing, only Webkit and Opera support this input type. In Firefox and Internet Explorer, the browser will default to a simple textbox — not ideal!

Browser Support

Let’s use jQuery UI to compensate.


Step 2 – Download jQuery UI

The jQuery UI datepicker tool works wonderfully, and is a cinch to “install.” First, we download a customized version of jQuery UI, Visit the download page, and only check the “Core” and “Datepicker” items. Leave everything else unchecked.

Downloads Page

Click download, and you’ll receive a zip containing the necessary files. Transfer over the jQuery UI file as well as the CSS directory to your project.


Step 3 – Integration

With jQuery UI imported into our directory tree, we next need to include the necessary files – specifically the CSS and JavaScript files.


<!DOCTYPE html>

<html lang="en">
<head>
   <meta charset="utf-8">
   <title>Datepicker</title>
   <link href="css/redmond/jquery-ui-1.8.13.custom.css" rel="stylesheet" />
</head>
<body>

<input type="date" name="date" id="date" value="" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script src="js/jquery-ui.js"></script>

</body>
</html>

Notice how we’ve included our custom jQuery UI stylesheet, the jQuery library – currently at version 1.6 – and the customized jQuery UI script, which I’ve renamed to jquery-ui.js.


Step 4 – The datepicker Method

Our base is set; now we need to query the DOM for the desired input element, and call the datepicker() method on it.

<script src="js/jquery-ui.js"></script>
<script>

$('#date').datepicker(); 

</script>

These few characters alone will do the trick. If we now view the page in Firefox and click on the input element, you’ll see the datepicker in effect.

Datepicker Control

Step 5 – Providing the Fallback

What we have here works, but there’s one problem. If we return to an advanced browser like Chrome, we’re now on double duty. Both the native and fallback datepickers are in effect, simultaneously. We need a way to specify that, if the browser supports the date input type, don’t do anything. That’s easy!

<!DOCTYPE html>

<html lang="en">
<head>
   <meta charset="utf-8">
   <title>Datepicker</title>
   <link href="css/redmond/jquery-ui-1.8.13.custom.css" rel="stylesheet" />
</head>
<body>

<input type="date" name="date" id="date" value="" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script>
   (function() {
      var elem = document.createElement('input');
      elem.setAttribute('type', 'date');

      if ( elem.type === 'text' ) {
         $('#date').datepicker();
      }
   })();

</script>
</body>
</html>

In a real-world project, you’d likely abstract away this testing code to its own method, or use Modernizr, but this will do the trick for testing purposes.

In the code above, we first create an input element, and then attempt to set its type attribute equal to date. Now if the browser fails at doing so — meaning that it doesn’t understand what the date type is — we can then assume that it’s an older browser, and provide the jQuery UI fallback instead. Simple!


Step 6 – Datepicker Options

The datepicker tool comes with a variety of overrides; you can review the entire list here.

Let’s examine a couple together. What if want to specify a specific date format. Rather than Y/M/D, we’d rather use Y-M-D. To do so, we use the dateFormat property.

$('#date').datepicker({
   dateFormat: 'yy-mm-dd'
});

Well that was easy. Next, let’s say that we only want the user to be able to select a date between now and four days from now. This is a cinch when we use the maxDate option. One handy-dandy feature is that we can use relative terms, such as +4, for four days from now.

$('#date').datepicker({
   maxDate: +4
});

We’re only scratching the surface here, but this should get you started! Cross-browser datepickers within minutes!

Add Comment

Discussion 45 Comments

  1. Andrew Ckor says:

    Nice tutorial Jeffrey! I like that day to day the jQuery solution is the fallback way :P An the HTML5 the plain way ! :)

  2. Very nice quick tip. Although, I don’t particularily like the datepicker on Chrome, I think jQuery UI is better. Now the worst that can happen is a non-modern browser with javascript disabled. :(

    • I agree with you on the issue of Chrome’s appearance, Jeremy. As for the non-modern, non-js users, would it be possible to hard-code in a sample date as a default value (i.e “2010-12-31″ to show you want it in yy-mm-dd format), and then remove it with your JavaScript when you’re doing the testing and manipulation? It doesn’t seem like it would be hard, just a line or two of code.

    • Eli Mitchell says:

      It will fall back to a text input which is fine as long as they enter a date in the correct format. Because of this, you should validate the date’s format on the server side.

    • Eli Mitchell says:

      It will fall back to a text input which is fine as long as they enter a date in the correct format. Because of this, you should validate the date’s format on the server side.

  3. nice tut
    thanks for share Jeffrey

  4. BlaineSch says:

    I’d hardly call it a “fall back”. What about non-js users? This is more of a jQuery datepicker tutorial.

    You should have a few dropdowns if you want to actually support users.

    <div id=”nojs” class=”visibleEl”>
    <select name=”month” id=”month”>
    <option value=”1″>January</option>
    <!– more options –>
    </select>
    <select name=”day” id=”day”>
    <option value=”1″>1</option>
    <!– more options –>
    </select>
    <select name=”year” id=”year”>
    <option calue=”2011″>2011</option>
    <!– more options –>
    </select>
    </div>
    <div id=”js” class=”hiddenEl”>
    <input type=”date” name=”date” id=”date” value=”" />
    </div>
    <script type=”text/javascript”>
    (function($) {
    $(‘#js, #nojs’).toggleClass(‘hiddenEl’).toggleClass(‘visibleEl’);
    // The rest of your code
    })(jQuery);
    </script>

    • Jeffrey Way says:
      Author

      It’s just a matter of how far you want to take it.

      • Dave says:

        I agree I’ve been using the jquery UI datepicker for ages very simple and works really well, I don’t cater for people having JS disabled you have to draw the line somewhere.

    • Peter says:

      I don’t see any fallback for users without Internet. And where is the fallback for people without a computer?

      • Javier says:

        LOL this comment rocks

      • BlaineSch says:

        If they can get to your site, it should work.

        But you’re right, if a customer who wants to buy your product doesn’t have JavaScript, let’s go ahead and make sure they can’t checkout since the date field will rarely be in the right format.

        Makes perfect sense.

      • Chris Sanders says:

        There is no way to do this without javascript. You have to have them enter in a date.

  5. Rick says:

    Am I the only person that doesn’t like jQueryUI? :/

    Sure it gets the job done, but it makes a hell of a mess of it. For example, a simple button in jQueryUI requires SEVEN css classes once built! You could build something identical in one, maybe two classes.

    I really don’t understand why they cant make it run better. If you inspect source (not view source) on one of the jQueryUI demo pages you’ll see its a complete mess.

    The second thing I really hate about it is that nobody has been able to come up with any innovative designs for it. They all look identical with border colors and background colors/images changed.

    I’m really disappointed that we’re stuck with no alternative to jQueryUI (jQuery Tools isn’t really an alternative, its just as bad).

    • David Ferguson says:

      You’re complaining about the number of classes it uses? Are you just looking for something to complain about? Of course if can be done in fewer. It requires more with UI because they have so much of their code broken up into multiple classes so the pieces can be used on multiple items. It prevents duplicating the same css code in a lot of different places.

    • Stefan says:

      well then this tiny (11Kb, one-file only, highly configurable) date picker is for you: http://stefangabos.ro/jquery/zebra-datepicker

  6. I love fallback mechanisms. I think they are the glue between modern browsers and old browsers and they let you use modern browsers, while you can also get sure that your site can be seen and interacted with in older browsers.
    One big problem is that, jQuery UI would also gets loaded for modern browsers, while it has no use at all in this sample. In other words, I think the best way is to detect feature (Feature Sniffing), and load jQuery only and if only browser doesn’t support date field type. This way, our page won’t get heavy for modern browsers.

  7. abdullah says:

    nice tric…
    I really need it…

  8. Good tutorial – I did a similar one a while back: http://nicolahibbert.com/form-widgets-jquery-ui/

    @Rick I agree that there’s a lack of options, but the jQTools calendar is much more painful to work with than the jQUI one imo :)

  9. Jatin says:

    Don’t mind, but I don’t like date-picker from jQuery UI.

    I like one mentioned here ( http://keith-wood.name/datepick.html )

  10. Jason says:

    Thank you for that tut, I will use it in current project.
    Jeffrey, can you please tell me, what is that font you use on that image http://d2o0t5hpnwv4c1.cloudfront.net/985_datepicker/browser-support.png

  11. newbie says:

    My input field has: 2011-05-25 14:34:46

    How can I modify this line w/ this nice Datepicker? Is it difficult?

    Thanks!

  12. w1sh says:

    Nice tut Jeffrey. Always liked the way you did tuts. Wish you’d knuckle down on Ruby or Python and start delivering some Rails or Django tuts.

    What is your preferred language anyway? PHP?

  13. As always Jeffrey – you posted this a couple of hours before i needed it :D Thanks for always reading my mind!
    - And by the way, which theme is it you’re using in you macvim

  14. Nicolas says:

    Hey,

    nice tutorial, fast, simple, easy!

    One question concerning MacVim though, around 6:10 you selected the date-picker method and moved it around, without deleting and pasting.. How did you do that ?

    • Jeffrey Way says:
      Author

      Hey Nicolas – Add this to your vimrc file:

      “Bubble single lines (kicks butt)
      “http://vimcasts.org/episodes/bubbling-text/
      nmap <C-Up> ddkP
      nmap <C-Down> ddp

      “Bubble multiple lines
      vmap <C-Up> xkP`[V`]
      vmap <C-Down> xp`[V`]

  15. teebee says:

    Always great tuts, fast, concise, and I’m always learning new things.

    Thanks Jeffrey!

    teebee :o]

  16. Joris says:

    “In a real-world project, you’d likely abstract away this testing code to its own method, or use Modernizr, but this will do the trick for testing purposes.”

    Would it be possible to provide an example of this?

    Nice tutorial btw, definitely using it next time I need something like this!

  17. Rick says:

    Nice Tut. Thank you.

    Question in another matter, but viewed in your tut. What did you use to have the finder split when you were moving the files from one window to the other?

    It is a nice feature to have for all of us Mac users.

    Thanks for the tut.

  18. Kevin says:

    Does anybody have any great recommendations for mobile data/time pickers that are cross (mobile) platform?

    I know jQuery Mobile has this, but I don’t want to fully implement jQuery mobile.

  19. Blake says:

    Thanks for this quick tip Jeffrey, makes my life a whole lot simpler rather than having to scourer the web for a cross-functional date picker.

  20. Eli Perelman says:

    If it were me making this, I would give all date pickers a class of datepicker and provide the fallback like so:

    $(‘.datepicker:not([type="date"])’).datepicker();

  21. Paul Irish says:

    Modernizr’s `inputtypes.datepicker` boolean will give you a false result for what’s currently shipping in Chrome/WebKit.

    There are two reasons: 1) the implementation isn’t complete and dealing with that spinner controls sucks if you’re actually trying to pick a date. 2) input value sanitization isn’t being applied to the input yet.

    So until those two things land (and I’ve received confirmation they will land together), Modernizr will tell you that WebKit does not support input type=date, which is my preferred outcome, so I can be sure everyone gets a datepicker widget.

    Other than that, I loved this… (though I would probably load jQuery UI with yepnope.. :)

    • Good to know this is on the list of the Chrome-devs. I prefer the current behavior of modernizer as well. Because only arrows instead of a true date picker are not as intuitive.

    • Jeffrey Way says:
      Author

      Yeah – was going to cover a script loader, but didn’t want to cover too much for a quick tip. Anyhow – agreed. Guys, if you’d like to use yepnope.js in the example above, use this script instead:

      yepnope({
         test : (function() {
            var elem = document.createElement('input');
            elem.setAttribute('type', 'date');
            return elem.type === 'date';
         })(),
         nope : 'js/jquery-ui.js',
         callback : function() {
            $('#date').datepicker({
               dateFormat: 'yy-mm-dd',
               // defaultDate: +5
               maxDate : +3
            });
         }
      });
      
  22. LastRose says:

    Great tut, though I prefer just sticking to a datepicker (jQueryUI or other) It helps normalize the appearance and functionality accross all browsers. The only nice implementation of the html5 date in my opinion is Opera.
    I would have preferred that all modern browsers implement it the same way, as it would make styling it that much easier, and also make it easier on end users, but since they haven’t, just keep type=text and jQueryUI it.

  23. Diogo Maia says:

    what is the name of the theme they use?

  24. DB says:

    Total Noob here. I am trying to the get the datetime to print in a format of “yy-mm-dd-T12:00Z” for mysql.

    I easily enough figured out the part of “yy-mm-dd-T”. It’s the latter that I am having trouble with.

    Any help is appreciated.

    Thank you in advance,
    DB

  25. RZV says:

    GREAT TUTORIAL . Thank you .

  26. Kenny says:

    Great info! One question I can’t figure out. How do I constrain the size of the datepicker? Do I really have to tweak the internals of the UI theme to do so? I couldn’t find an applicable option. Thanks.

  27. Josh says:

    Hey

    Hope this thread is still going.

    Came across this script. Was wondering if there was anyway we could limit this script so that it reads from todays date and 31 days back.

    So basically all the shows is todays date – 31 days. Trying to implement this into a warranty form. So that the users cant select a date that is older than 31 days from today.

    Hope that makes sense.

    Thanks

  28. Kęstutis says:

    Thank You for tutorial, it’s great. One thing i can’t manage, though. What if I need two datepicks in one window. I can’t make it work in these conditions. Any suggestions?

Add a Comment

To add a code snippet to your comment, please wrap your code like so: <pre name="code" class="html">YOUR CODE</pre>. You can replace the class name with "js," "css," "sql," or "php." If there are any "<" or ">" within your code, please search and replace them with: &lt; and &gt; respectively.