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 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 add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
Steps to Secure a VPNMiscellaneousadd_filter function in WordPressWordPressNumber Properties in JavaScriptJavaScriptWordPress: How to add a Search Icon in Menus with toggle effect using jQuery?jQueryWhat does Containment mean in React?ReactIntroduction to components and templates Part 3: Data bindingAngularQuery to increment or decrement value in MySQL ignoring negative valuesSQL/MySQLSolution to “NullInjectorError: No provider for module” in Angular 9AngularHow to overwrite file contents with new content in PHP?PHPbin2hex() and chr() String Functions in PHPPHPHow to add onclick event to html elements dynamically using JavaScript?JavaScriptKilling A Project Part 1: What criteria should be used to cancel/kill a project?Miscellaneous