YogeshChauhan.com

How to add today’s date in HTML input date value using JavaScript?

March 23, 2021

Quick Solution

There are multiple ways to do that. Here are couple of examples:

Exploring the examples above

I have used toISOString method in JavaScript to get a Date object as a String. The toISOString method uses ISO standard.

On a side note, you can convert datetime to date format using toDateString.

Let’s look at this code and the result:

I used the querySelector to get the element, doesn’t really matter matter what method you use to get the element .

The toISOString method gives us nice string that we can use to extract the date from.

So, as we saw in the example 1, all we need to do is get the first 10 characters from the ISO date string using substr method.

On a side note, there is a difference between substr and substring methods.

In the second example, I used valueAsDate method that returns or sets the value of the element as a date.

If conversion is not possible then it will set the value as null.

dreamhost

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to uninstall Cocoapods from the Mac OS? #4 How to Use SQL MAX() Function with Dates? #5 How to add Read More Read Less Button using JavaScript? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Apr 7 Solution for “Yarn build: Failed because of a stylelint error” Apr 7 Make sure your links have descriptive text Apr 7 How to add Laravel to WordPress using Sage theme (and install Tailwind CSS)? Apr 2 How to create a sidebar using pure CSS? Apr 1 How to switch dark and light themes using pure CSS? Apr 1 How to calculate elapsed time in JavaScript?

You might also like these

Solution to “TypeError: ‘x’ is not iterable” in Angular 9AngularLearn to create your skill bar using CSSCSSHow to set the permissions on all files and folders in Mac?MiscHow to create a dynamic countdown using HTML and JavaScript?HTMLJavaScript String fromCharCode() MethodJavaScriptThe Sort and Compare Functions in JavaScriptJavaScriptHow to Find the Highest (or Lowest) Number in an Array in JavaScript?JavaScriptHow to add a Pie Chart in Angular App?AngularHow does AdSense calculate page loading time?JavaScriptHow to control file extensions with an .htaccess file?MiscShould we ever delete data from a database?MiscHow to add and remove list items using JavaScript?JavaScript