Smoother CakePHP date/time fields with jQuery

While working with the date/time input fields in Cake I got tired of having to select 3/6 drop down boxes to choose all of the date/time information and specifically of having to select 3/6 drop down boxes if I decided to clear the date. A little bit of jQuery will clear this right up though.

Just add this this piece of jQuery code and all of your drop down boxes will gain the following behavior:

  • If all of the values are blank and you choose a value for any of them, all the others will be set to the first value in the list - except for the year which will become the current year.
  • If you set any of the values back to the empty cell, all of them will select the empty cell.

Now just drop in this jQuery code and you should be good to go.

   $('div.input.datetime select').change(function() {
      if($(this).val() == '') {
      else {
         $(this).siblings('select').each(function(sel) {
            if($(this).val() == '') {
               if($(this).attr('id').indexOf('Year') != -1) 
                  $(this).val((new Date()).getFullYear());
               else this.selectedIndex = 1;               

This article has also been publish at The Bakery.

About Me

My name is Barry Jones and Brightball, Inc was my contract development company from 2008-2012. Although I no longer do contract work this site has become my personal blog.

If you enjoy my writing and want to support the habit please use my referrals to help me pay for my servers with Digital Ocean, my DNS with DNS Made Easy, my email with Sendwithus and my focus with Freedom.

You're also welcome to buy some things that I highly recommend, such as the best movie ever made, a hilarious cookbook for microwave dependent men like myself, the best travel laptop backpack I've ever owned, an awesome lap desk, some of the best headphones out there for the money or maybe an iPad Mini for the kids?

If you just came here to learn by all means keep it up. Grab a book on Elixir, Phoenix, Go, encryption throughout history, hacking stories or running a business. Thanks!

Follow Me

  • Twitter
  • LinkedIn
  • slideshare
  • StackOverflow
  • Github
  • RSS