How to make jqueryUI datepicker submit in a different format than what is being displayed?

Solution 1:

There's 2 configuration options for that: altField and altFormat. http://api.jqueryui.com/datepicker/#option-altField If you specify an altField, that field will be updated too, and will have the altFormat. Normally you will want make the altField a hidden field, soyou can ignore the regular field and send to db the altField.

Solution 2:

As you'll have noticed, supplying a dateFormat works well for newly entered dates, but it does not alter the value attribute which was already supplied to the date input field. It took me some time and I'm not sure whether this solution is ideal, but here's my situation explained and the code which solves it. Might help others with the same problem in the future. In my example I'm using dd/MM/yyyy as the display format.

  1. The page contains any number of date input fields, which may or may not already have a value attribute supplied in the format yyyy-MM-dd, as specified by W3C.
  2. Some browsers will have their own input control to handle dates. At the time of writing, that is for instance Opera and Chrome. These should expect and store a date in the abovementioned format, while rendering them according to the client's regional settings. You probably do not want/need to create a jqueryui datepicker in these browsers.
  3. Browsers which don't have a built-in control to handle date input fields will need the jqueryui datepicker along with an 'alt', invisible field.
  4. The invisible, alt input field with the yyyy-MM-dd format must have the original name and a unique id in order for forms logic to keep working.
  5. Finally, the yyyy-MM-dd value of the display input field must be parsed and replaced with its desired counterpart.

So, here's the code, using Modernizr to detect whether or not the client is able to natively render date input fields.

if (!Modernizr.inputtypes.date) {
    $('input[type=date]').each(function (index, element) {
        /* Create a hidden clone, which will contain the actual value */
        var clone = $(this).clone();
        clone.insertAfter(this);
        clone.hide();

        /* Rename the original field, used to contain the display value */
        $(this).attr('id', $(this).attr('id') + '-display');
        $(this).attr('name', $(this).attr('name') + '-display');

        /* Create the datepicker with the desired display format and alt field */
        $(this).datepicker({ dateFormat: "dd/mm/yy", altField: "#" + clone.attr("id"), altFormat: "yy-mm-dd" });

        /* Finally, parse the value and change it to the display format */
        if ($(this).attr('value')) {
            var date = $.datepicker.parseDate("yy-mm-dd", $(this).attr('value'));
            $(this).attr('value', $.datepicker.formatDate("dd/mm/yy", date));
        }
    });
}