Yogesh Chauhan's Blog

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

in JavaScript on 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.


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
The Drupal flowDrupalHow does Next.js load pages faster?NextJSHow to add and remove capabilities from a role in WordPress?WordPressHow to redirect or load a new document using JavaScript?JavaScriptHow to Install PHP Laravel on MacOS Catalina?PHPWindow setInterval() Method in JavaScriptJavaScriptJavaScript String Properties and MethodsJavaScriptHow to auto-resize textarea based on text input using JavaScript or jQuery?JavaScriptWhat are Modules and Components in Angular?AngularPostgreSQL BETWEENPostgresWhat is React? Learn the basicsReactCan we execute conditions in SQL?SQL/MySQL