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");
}
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.
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);
});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}`;
}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"
});aria-expanded.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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.