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 Solid
- Getting Started with Express
- Create an RSS Reader in Node
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to build a Discord bot using TypeScript
- Getting Started with Deno
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Using Push.js to Display Web Browser Notifications
- Setting Up a Local Web Server using Node.js