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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #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

#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 #Jan 14 How to display a student’s individual transcript in Colleague? #Jan 11 How to install PuTTY on a MacOS?
You might also like these
How to Install PHP Laravel on MacOS Catalina?PHPIs there a CSS parent selector?CSSHow to create an empty array in Swift?SwiftHow to convert an object from API to JSON array in Angular 9?AngularHow to add Local State to a Class in React?ReactThe Sort and Compare Functions in JavaScriptJavaScriptHow to convert an HTML radio buttons into a toggle switch using CSS?CSSHow to apply style to the first-child using jQuery?jQuerySelector Lists and Combinators in SCSS (Sass)SCSSOOP, Class and Objects Strategies For Beginners (PHP)PHPLearn to Implement Estimated Reading Time using PHP Part 1: The BasicsPHPHow to show slider value in HTML5 range input using JavaScript?HTML