How to Get and Set a Date from DOM Input using JavaScript

Updated onbyAlan Morel
How to Get and Set a Date from DOM Input using JavaScript

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:

JAVASCRIPT
const dateInput = document.querySelector("#date");

Now, let's attach the event listener:

JAVASCRIPT
const 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:

JAVASCRIPT
const 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:

JAVASCRIPT
const dateInput = document.querySelector("#date");

Now, we can set the value of the input element by using the built-in valueAsDate property:

JAVASCRIPT
const 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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.