Using HTML Native Date Picker with JavaScript

Updated: March 30, 2023 By: Goodman Post a comment

The HTML native date picker is an input element with type=“date” that allows the user to enter a date, either with a textbox or a special date picker interface. It is supported by all major modern browsers, including Chrome, Microsoft Edge, Safari, Firefox, etc. The value of the input is formatted as yyyy-mm-dd according to ISO86011. The input can have additional attributes such as min, max, and step to specify the range and granularity of the date.

In this practical article, we will use JavaScript to listen to the change event of a date input, which fires when the user selects a date from the date picker or enters a valid date in the input field. We will also use JavaScript to programmatically manipulate the date input (set the start date and the end date so that the user can only choose a date from a limited range).

Example preview:

The complete code (with explanations in the comments):

<html>

<head>
  <title>Sling Academy</title>

  <!-- CSS -->
  <style>
    input[type="date"] {
      border: 1px solid gray;
      border-radius: 4px;
      padding: 5px;
      font-size: 16px;
    }

    #result {
      margin-top: 10px;
      font-size: 24px;
      color: blue;
    }
  </style>
</head>

<body>
  <h3>Please select a date</h3>
  <!-- the date picker -->
  <input type="date" id="date-input">

  <!-- The selected date will be shown here -->
  <div id="result"></div>

  <!-- JavaScript code -->
  <script>
    // Get the input element
    let input = document.getElementById("date-input");

    // Define the start date (min date) and end date (max date)
    let startDate = new Date("2023-01-01");
    let endDate = new Date("2023-12-31");

    // Set start date and end date for the input element
    input.min = startDate.toISOString().slice(0, 10);
    input.max = endDate.toISOString().slice(0, 10);

    // Listen to the date input value when it changes
    input.addEventListener("change", function () {
      // Get the selected date
      let selectedDate = new Date(input.value);

      // Display the selected date in the result div
      const result = document.getElementById("result");
      result.innerHTML = selectedDate.toLocaleString(
        "en-US",
        {
          weekday: "long",
          year: "numeric",
          month: "long",
          day: "numeric",
        }
      );
    });
  </script>
</body>

</html>

That’s it. Happy coding & have a nice day!