Search code examples
javascriptformsgoogle-chromedatejs

Autofilling Form Date and Time in Chrome with Javascript


I'm trying to populate a form on a site with values passed through GET. The two fields I'm having trouble with are input tags that are of type type="date" or type="time". Chrome has this nice feature that gives you a drop down calendar to select a date:

Chrome's Drop Down Calendar for Date Inputs

Chrome also does something similar for the Time field. The problem is that it doesn't like javascript that tries to populate those types of form fields. I pass GET information like so:

Passed Information through GET to Populate the Form Fields

The reason the date is formatted like this is because that's what the back-end requires (not what I'm working on) and the date comes directly from the back end code.

I have a function that auto-populates document.$_GET as an array with all passed values from GET. I also have date.js included, which allows me to use the Date.parse functionality and some other stuff. I pass it through javascript like this:

if(document.$_GET['time']!=undefined)
  document.getElementById('time').value=document.$_GET['time']; 

if(document.$_GET['date']!=undefined){
  var date = new Date();
  date = Date.parse(document.$_GET['date']);
  alert(date.toString('MM-dd-yyyy')); // <-- Debugging
  document.getElementById('date').value = date.toString('MM-dd-yyyy'); //WHY WON'T YOU WORK!?
}

On Safari I get what I expect to get:

Autofilled form in Safari

With Chrome I'm left with empty form fields:

Empty fields in Chrome

I'm stumped and not sure how to remedy this. I need Chrome to autofill similar to how Safari does.


Solution

  • Google Chrome is strict about the format of the Date.

    The date works with the following format, YYYY-MM-DD. The time works with military time. (24h clock)

    Here's a sample, http://jsfiddle.net/vFnxw/2/

    $("#date").attr({
        value:"2012-09-28"
    })
    $("#time").attr({
        value:"23:59:59"
    })
    

    Here are the sources

    http://dev.w3.org/html5/markup/input.date.html

    http://dev.w3.org/html5/markup/input.time.html