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 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

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
INNER JOIN in PostgresPostgresWhat is Prototypal Inheritance in JavaScript?JavaScriptHow to use images instead of HTML radio buttons using CSS?CSSHow to get category name using post id in WordPress?WordPressHow does while loop work in SCSS?SCSSFunction Scope in JavaScript for BeginnersJavaScriptHow to get current timestamp in Swift 4 and 5?SwiftLearn to Make a Simple Contact Us Form using PHP and PDO-MySQLPHPWordPress: How to loop through a repeater field in ACF?WordPressHow to get ACF values from custom post type?WordPressMake sure your links have descriptive textUI/UXAngular 9 time clock update every minute, second, hourAngular