Copy a Calendar Date to an Input with JavaScript

This project extends the monthly calendar by making each day selectable. When the user chooses a date, JavaScript formats the selected year, month, and day and places the value in a text field.

function returnValue(year, monthIndex, day) {
  const selected = new Date(year, monthIndex, day);
  document.getElementById("t1").value = selected.toLocaleDateString("en-CA");
}

Start from the Monthly Calendar Top ↑

This tutorial builds on the current-month calendar. The first weekday and last date calculations stay the same; only the content placed in valid date cells changes.

Make Each Calendar Date Selectable Top ↑

The historical version generated an anchor with an inline onclick. A button is more appropriate because choosing a date performs an action rather than navigation, and attaching the event with JavaScript keeps behavior out of the HTML string.

const choose = document.createElement("button");
choose.type = "button";
choose.textContent = day;
choose.addEventListener("click", () => {
  returnValue(year, month, day);
});

Return the Selected Date to the Input Top ↑

Remember that JavaScript month indexes are 0–11; see getMonth() for the month-index rules. If you display a numeric month, add 1 before formatting it.

function formatDate(year, monthIndex, day) {
  const month = String(monthIndex + 1).padStart(2, "0");
  const date = String(day).padStart(2, "0");
  return `${year}-${month}-${date}`;
}

Choose an Unambiguous Date Format Top ↑

The old demo returned month/day/year. That can be ambiguous internationally. For machine-readable form values, YYYY-MM-DD is clearer; for user-facing text, format the Date for the intended locale.

const selected = new Date(year, monthIndex, day);
const label = selected.toLocaleDateString("en-US", {
  year: "numeric", month: "long", day: "numeric"
});

Accessibility and Form Behavior Top ↑

  • Use real buttons for selectable dates so keyboard users can activate them.
  • Give the calendar a clear trigger with aria-expanded.
  • Keep the selected value in a named form control if it must be submitted.
  • Validate the submitted date on the server even if the picker restricts the UI.

Complete Working Demo Top ↑

Open the Calendar-to-Input Demo

For the next step, see the calendar with month/year navigation and then the linked start/end date calendars from Date Projects.

Date Reference All Date Projects




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer