Categories: Development

Setting HTML date input value

How to set the default value to a HTML date input using vanilla JS or jQuery, including a method to set the date to be 1 month from now.

The date input element:

<input type="date" id="todaysDate" name="todaysDate">

Full example and code.

Setting the value to be today’s date with vanilla JS:

document.getElementById("todaysDate").valueAsDate = new Date();

Custom date with jQuery:

$("#customDate").val("2004-08-15");

Or setting a custom date such as one month from today’s date:

var the_date = new Date();
the_date.setMonth(1);
var yyyy = new Intl.DateTimeFormat("en", { year: "numeric" }).format(the_date);
var mm = new Intl.DateTimeFormat("en", { month: "2-digit" }).format(the_date);
var dd = new Intl.DateTimeFormat("en", { day: "2-digit" }).format(the_date);
var one_month_on = `${yyyy}-${mm}-${dd}`;

$("#oneMonth").val(one_month_on);

setMonth(1) is for setting the date to 1 month in advance. setMonth(6) would be 6 months advanced.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago