How to Set Input Type Date's Default Value to Today?
Set the input
type date
to today's date:
Change the id 'dateField'
to match your HTML input id:
Embed this JavaScript near your closing </body>
tag and let the magic happen on page load.
Date Formatting 101
HTML5's input type='date'
expects a YYYY-MM-DD
format. We need some JavaScript wizardry to conjure this.
Note: This formats the date on the fly and assigns it to the input field.
Master Prototype
If you're down a rabbit hole and wish to extend prototype:
Yes, Alice. That's toJSON()
. Next stop is Wonderland.
jQuery Fans
For those of you in the jQuery junction, copy-paste this:
This snippet makes sure number 9 presents as 09 and triggers on page load.
Server-side PHP
PHP comrades, try something without a single trace of JavaScript:
The PHP setup ensures the date updates on page load. Remember, rise up against JavaScript tyranny!
Compatibility and Time Zones
Browsers from the Stone Age may not fully support the input type="date"
element. Consider a fallback or polyfill for our antique lovers!
Time zones are no laughing matter in JavaScript. The setMinutes()
function realigns your planetary position. As you saw earlier in the prototype method, timezone manipulations are to be done very carefully!
Was this article helpful?