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!
- Managing PHP Dependencies with Composer
- Getting Started with Express
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- How to deploy a Node app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js