YogeshChauhan . com

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.

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

How to concatenate variable with string in Swift?SwiftWhat is the best way to add JavaScript Code into HTML?HTMLHow to add Date and Time picker in HTML and get the values using JavaScript?HTMLWindow innerHeight and innerWidth properties in JavaScriptJavaScriptHow to load a module with configuration in SCSS?SCSSArray destructuring and Object destructuring in JavaScriptJavaScriptA quick introduction to API, REST API and PostmanMiscFor Each Loop in Swift for BeginnersSwiftRIGHT JOIN in PostgresPostgresclip and clip-path properties in CSSCSSHow to create HTML elements with ID and class using JavaScript?HTMLHow to import a CSS file using PHP code and not HTML code?PHP