Seamless Rails integration with jQuery Tools Dateinput

Posted by Paul McMahon on 2010-11-19

Rails default date input is functional, but not very user friendly. For instance, the following is what date input previously looked like in Doorkeeper.

However, by using the Javascript library jQuery Tools' Dateinput, I changed improved the user interface to the following.

The issue with Dateinput, and other date selection widgets, is that they don't use the Rails style drop downs for inputs, but rather a text input (or HTML 5's date input in the case of Dateinput). To work around this, there are two general strategies: adapt your Rails application to support text inputs for dates, or adapt the widget to use Rails date drop downs. I prefer the second strategy as it is overall much less intrusive.

To accomplish this, I adapted a snippet I found for adapting jQuery UI's datepicker to Rails to the following which is available as a gist.

// Based on http://snipt.net/boriscy/datetime-jquery-formtastic/ $.tools.dateinput.localize("ja", { months: '1月,2月,3月,4月,5月,6月,7月,8月,9月,10月,11月,12月', shortMonths: '1月,2月,3月,4月,5月,6月,7月,8月,9月,10月,11月,12月', days: '日曜日,月曜日,火曜日,水曜日,木曜日,金曜日,土曜日', shortDays: '日,月,火,水,木,金,土' }); $.tools.dateinput.conf.format = 'yyyy-mm-dd'; $(document).ready(function() { $.tools.dateinput.conf.lang = $('html').attr('lang'); $('div.date, div.datetime').each(function(i, el) { var sels = $(el).find("select:lt(3)"); var d = new Date(sels[0].value, parseInt(sels[1].value) - 1, sels[2].value); var dateinput = $(">input type="date" /<").dateinput({ value: d} ); // Without this, the field is initially blank dateinput.val(dateinput.data().dateinput.getValue($.tools.dateinput.conf.format)); dateinput.change(function(event, date) { $(sels[0]).val(date.getFullYear()); $(sels[1]).val(date.getMonth() + 1); $(sels[2]).val(date.getDate()); }); $(sels[0]).before(dateinput); $(sels).hide(); }); });

By just adding this javascript file, along with the base dateinput widget, you can convert all your date inputs to use the widget. No modification of any internal application or view logic required. The Japanese localization is also included, along with automatic locale switching based on the html's lang attribute.