How to Get and Set a Date from DOM Input using JavaScript
Table of Contents
JavaScript makes creating an interactive web page very easy, thanks to all of the built-in APIs that interface with the DOM.
One of the most common things to do is to ask for a user input for a date and then use that date for something else.
In this post, we'll learn how to get and set a date from the value of a DOM input element in JavaScript.
How to get a date from a DOM input element
To start, let's create some example HTML that one might find inside of a form:
HTML<form>
<label for="date">Date</label>
<input type="date" id="date" name="date" />
</form>
In our example, we just have a form that has just a single input field, the date input.
Now, we want to parse the date immediately, so to do that, we can listen for the input
event on the input element.
First, let's query for the input element:
JAVASCRIPTconst dateInput = document.querySelector("#date");
Now, let's attach the event listener:
JAVASCRIPTconst dateInput = document.querySelector("#date");
dateInput.addEventListener("input", event => {
// do something
});
Inside this event listener, we will want to get the value of the input element and then parse it into a JavaScript Date
object.
This is how we can do this:
JAVASCRIPTconst dateInput = document.querySelector("#date");
dateInput.addEventListener("input", event => {
const date = new Date(event.target.value);
});
That's it, we've now parsed the date from the input element.
How to set a date on a DOM input element
Now let's say the situation is reversed and we instead have a Date object but want to set the value of the input element to that date.
We can do this by first querying for the input element:
JAVASCRIPTconst dateInput = document.querySelector("#date");
Now, we can set the value of the input element by using the built-in valueAsDate
property:
JAVASCRIPTconst dateInput = document.querySelector("#date");
dateInput.valueAsDate = new Date();
This property lets you set the default value of the input element to a JavaScript Date
object.
Conclusion
In this post, we learned how to get and set a date from the value of a DOM input element in JavaScript.
Simply parse the date from the input element by listening for the input
event and then set the value of the input element by using the valueAsDate
property.
Thanks for reading!
- Getting Started with TypeScript
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Svelte
- Getting Started with Express
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- How to deploy an Express app using Docker
- Getting Started with Handlebars.js