I have implemented this solution to my school project
However I get this error from the console whenever I attempt to change the value of the initial date field
The specified value "2/21/2023" does not conform to the required format, "yyyy-MM-dd".
What could be wrong in the solution as it works in the example given
I tried change the
dueDateInput.value = dueDate.toLocaleDateString('en-CA');
into
dueDateInput.value = dueDate.toISOString();
and also
dueDateInput.value = dueDate.toLocaleDateString('bo-CN');
but to no avail
Since the browser says that this is the codeline that gives the error, how can I convert the dueDate to YYYY-MM-DD so that I can assign it as the value to the other date field
You can avoid using date strings and simply set the valueAsDate property instead.
This allows you to work directly with Date
instances which makes date arithmetic much easier.
const dateCreatedInput = document.getElementById("date-created");
const addMonthsInput = document.getElementById("add-months");
const dueDateInput = document.getElementById("due-date");
const setDueDate = () => {
const dateCreated = dateCreatedInput.valueAsDate;
if (dateCreated) {
dateCreated.setMonth(dateCreated.getMonth() + addMonthsInput.valueAsNumber);
dueDateInput.valueAsDate = dateCreated;
}
};
dateCreatedInput.addEventListener("change", setDueDate);
addMonthsInput.addEventListener("change", setDueDate);
<p>
<label for="date-created">Date created:</label>
<input type="date" id="date-created"/>
</p>
<p>
<label for="add-months">Add months:</label>
<input type="number" id="add-months" min="1" value="1"/>
</p>
<p>
<label for="due-date">Due date:</label>
<input type="date" id="due-date" readonly/>
</p>