default value input date js

Default Value in Input Date JS

Input date is a type of input field in HTML that allows the user to select a date from a calendar. In JavaScript, we can set a default value for this field using the value attribute. This default value will be displayed in the input field when the page loads, and the user can change it if they want to.

Setting Default Value with JavaScript

If you want to set a default value for the input date field using JavaScript, you can do it like this:


let today = new Date().toISOString().substr(0, 10);
document.querySelector("#myDate").value = today;

In this example, we are creating a new Date object and converting it to an ISO string format. We then use substr() to extract the date part of the string (which is the first 10 characters) and assign it to the variable today. Finally, we set the value of the input field with ID myDate to be the value of today.

Setting Default Value with HTML

If you want to set a default value for the input date field using HTML, you can do it like this:


<input type="date" value="2021-01-01">

In this example, we are using the value attribute to set the default value of the input date field to be January 1st, 2021. You can change this value to any date format that is supported by the input date field.

Conclusion

Setting a default value for the input date field can be useful when you want to provide a pre-selected date to the user or when you want to simplify the process of selecting a date. You can set the default value using JavaScript or HTML, depending on your preference and requirements.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe