Categories
JavaScript Answers

How to set date in input type date with JavaScript?

Spread the love

You can set the date in an <input type="date"> element using JavaScript by setting the value attribute of the input element to a string representing the desired date in the format “YYYY-MM-DD”.

For example, we write:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Set Date Input with JavaScript</title>
</head>
<body>
<label for="dateInput">Select a Date:</label>
<input type="date" id="dateInput">
<button onclick="setDate()">Set Date to Today</button>

<script>
function setDate() {
  const today = new Date();
  const year = today.getFullYear();
  const month = (today.getMonth() + 1).toString().padStart(2, '0'); // Month is zero-based
  const day = today.getDate().toString().padStart(2, '0');

  const dateString = `${year}-${month}-${day}`;
  document.getElementById('dateInput').value = dateString;
}
</script>
</body>
</html>

In this example, clicking the “Set Date to Today” button will set the value of the <input type="date"> element to today’s date.

The setDate() function constructs a string representing today’s date in the “YYYY-MM-DD” format and sets it as the value of the input element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *