Default Value to Today?

The new HTML5 input types are great. Opera's new built-in date picker is a breeze, and Chrome has at least supported the new input type with a spin-wheel implementation.

But is there any way to set the default value of the date field to today's date? With Opera, I can choose 'Today' from the date picker, and as soon as I click on either of the step buttons in Chrome, it increments/decrements from today's date.

I'm not shy to code a solution to this minor problem, but it seems silly to me that both of the browsers are fully aware of the current date but won't automatically just pop it in (at least as a placeholder).


Like any HTML input field, the browser will leave it empty unless a default value is specified with the value attribute.

Unfortunately HTML5 doesn't provide a way of specifying 'today' in the value attribute (that I can see), only a RFC3339 valid date like 2011-09-29 . Sorry, that doesn't help much!


The JavaScript Date object provides enough built-in support for the required format to avoid doing it manually:

Add this for correct timezone support:

Date.prototype.toDateInputValue = (function() {
    var local = new Date(this);
    local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
    return local.toJSON().slice(0,10);
});


jQuery:

$(document).ready( function() {
    $('#datePicker').val(new Date().toDateInputValue());
});​


Pure JS:

document.getElementById('datePicker').value = new Date().toDateInputValue();

this works for me:

document.getElementById('datePicker').valueAsDate = new Date();

https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement

链接地址: http://www.djcxy.com/p/3078.html

上一篇: Java.util.Date与Java.sql.Date

下一篇: 默认值为今天?