HTML DOM datetime-local
Object: Accessing Local Datetime Input Elements
The HTML DOM datetime-local
object provides an interface for interacting with <input type="datetime-local">
elements in your web pages. These input elements allow users to easily select a specific date and time, making them essential for applications requiring precise time-based data collection. This article will explore how to access and manipulate these elements using JavaScript and the Document Object Model (DOM).
What is the datetime-local
Input Type?
The <input type="datetime-local">
element renders a date and time input field that presents a user interface for selecting a local date and time. Unlike the date
and time
input types, this specific input type combines both date and time selection into a single control. This makes it ideal for capturing appointments, meeting times, and other events that are specific to a user’s local timezone.
Purpose of the HTML DOM datetime-local
Object
The primary purpose of the HTML DOM datetime-local
object is to allow JavaScript to access and manipulate the properties and behavior of <input type="datetime-local">
elements. This includes getting and setting the selected date and time, validating user input, and responding to user interactions.
Getting Started with datetime-local
Input
To utilize the datetime-local
object, you must first add an <input type="datetime-local">
element in your HTML. Assigning it an ID allows easy access through JavaScript.
<input type="datetime-local" id="myDatetimeLocal" name="eventDatetime">
Then, in your JavaScript code, you can access the element using document.getElementById()
:
const datetimeLocalInput = document.getElementById("myDatetimeLocal");
Now, datetimeLocalInput
is an HTML DOM datetime-local
object, which you can use to access its properties and methods.
Key Properties of the datetime-local
Object
Understanding the key properties of the <input type="datetime-local">
element is essential for effective manipulation:
Property | Type | Description |
---|---|---|
`value` | String | The current value of the datetime-local input, formatted as “YYYY-MM-DDThh:mm”. It can be used to get or set the date and time. |
`defaultValue` | String | The default value of the datetime-local input, as specified in the HTML. |
`min` | String | The minimum allowable date and time. Must be in “YYYY-MM-DDThh:mm” format. |
`max` | String | The maximum allowable date and time. Must be in “YYYY-MM-DDThh:mm” format. |
`step` | Number or “any” | The stepping interval for the time, in seconds. The special value `”any”` is used to disable stepping restriction. |
`form` | HTMLFormElement | Returns a reference to the parent form element. |
`name` | String | Returns or sets the name of the input element, used when submitting the form. |
`type` | String | Returns the type of the input element, which is always `”datetime-local”`. |
`validity` | ValidityState Object | Returns a ValidityState object containing information about the input’s validity. |
`labels` | NodeList | Returns a list of labels associated with the input element. |
`disabled` | Boolean | Returns or sets whether the input is disabled. |
`readOnly` | Boolean | Returns or sets whether the input is read-only. |
`required` | Boolean | Returns or sets whether the input is required for form submission. |
Note: The value
property uses the ISO 8601 format, which is essential for consistent and predictable date-time handling across applications. 🗓️
Basic Manipulations with datetime-local
Let’s explore some basic operations with the HTML DOM datetime-local
object. Each example below includes the necessary HTML and JavaScript code.
Getting and Setting the Value
The value
property can be used to both get and set the selected date and time of the input element.
<input type="datetime-local" id="datetimeInput1" name="eventTime">
<button onclick="getValue1()">Get Value</button>
<button onclick="setValue1()">Set Value</button>
<p id="output1"></p>
<script>
const datetimeInput_1 = document.getElementById('datetimeInput1');
const output_1 = document.getElementById('output1');
function getValue1() {
output_1.textContent = 'Current Value: ' + datetimeInput_1.value;
}
function setValue1() {
datetimeInput_1.value = '2024-12-25T10:30';
output_1.textContent = 'Value set to: 2024-12-25T10:30';
}
</script>
Output:
Initially, no value will be shown. Clicking on “Get Value” will output the current value (if any), and clicking “Set Value” will set the input to 2024-12-25T10:30
and show this set value.
Setting Min and Max Dates
The min
and max
properties can be used to set the range of allowable dates and times. This is helpful for ensuring that users select a date and time within a specific range.
<input type="datetime-local" id="datetimeInput2" min="2024-01-01T00:00" max="2024-12-31T23:59" name="meetingTime">
<p id="output2"></p>
<script>
const datetimeInput_2 = document.getElementById('datetimeInput2');
const output_2 = document.getElementById('output2');
datetimeInput_2.addEventListener('change', function() {
output_2.textContent = "Selected value: "+ datetimeInput_2.value;
});
</script>
Output:
The input field will only allow selection of dates between 2024-01-01T00:00
and 2024-12-31T23:59
. When you select any value in the input field, then the selected value will be shown under the input box.
Setting the step
Attribute
The step
attribute defines the increment at which the time values can be changed in the input control. If set to a number, the value will be treated as the step size in seconds. For the special any
value, all values are allowed.
<input type="datetime-local" id="datetimeInput3" step="60" name="appointmentTime">
<p id="output3"></p>
<script>
const datetimeInput_3 = document.getElementById('datetimeInput3');
const output_3 = document.getElementById('output3');
datetimeInput_3.addEventListener('change', function(){
output_3.textContent = "Selected Value: "+ datetimeInput_3.value;
});
</script>
Output:
The time picker will only allow times to be selected in one-minute increments (60 seconds), if you try to select other values, then it will be rounded off to nearest one minute. When you select a value in the input field, the selected value will be shown under it.
Accessing the Form Element
The form
property is useful when you want to interact with the form that contains the datetime-local
input element.
<form id="myForm">
<input type="datetime-local" id="datetimeInput4" name="deadlineTime">
</form>
<button onclick="getForm()">Get Form</button>
<p id="output4"></p>
<script>
const datetimeInput_4 = document.getElementById('datetimeInput4');
const output_4 = document.getElementById('output4');
function getForm() {
const form = datetimeInput_4.form;
output_4.textContent = 'Form ID: ' + form.id;
}
</script>
Output:
Clicking the “Get Form” button will output the ID of the form element, which is myForm
.
Validating Input with validity
The validity
property returns a ValidityState
object that provides detailed information about the validity of the input element. It’s particularly useful for form validation.
<input type="datetime-local" id="datetimeInput5" required name="eventStartTime">
<button onclick="validateInput()">Validate</button>
<p id="output5"></p>
<script>
const datetimeInput_5 = document.getElementById('datetimeInput5');
const output_5 = document.getElementById('output5');
function validateInput() {
const validity = datetimeInput_5.validity;
if (validity.valueMissing) {
output_5.textContent = 'Error: Please enter a value.';
} else {
output_5.textContent = 'Input is valid.';
}
}
</script>
Output:
Initially, if the input field is empty, clicking “Validate” will result in an error message. Once filled with some value, then clicking the validate will output Input is valid
Practical Use Cases
Scheduling Events
Using a datetime-local
input allows you to build a user-friendly interface for scheduling events in a web application.
<form id="eventForm">
<label for="eventDatetime">Select Event Date and Time:</label>
<input type="datetime-local" id="eventDatetime" name="eventDatetime" required>
<button type="submit">Schedule Event</button>
</form>
<p id="scheduleOutput"></p>
<script>
const eventForm = document.getElementById('eventForm');
const scheduleOutput = document.getElementById('scheduleOutput');
eventForm.addEventListener('submit', function(event) {
event.preventDefault();
const selectedDateTime = document.getElementById('eventDatetime').value;
scheduleOutput.textContent = 'Event Scheduled for: ' + selectedDateTime;
});
</script>
Output:
Users can select date and time, then the submitted value will be shown on the output.
Booking Appointments
The datetime-local
input can also be used for booking appointments, allowing users to select a convenient date and time slot.
<form id="appointmentForm">
<label for="appointmentTime">Select Appointment Time:</label>
<input type="datetime-local" id="appointmentTime" name="appointmentTime" required
min="2024-07-01T09:00" max="2024-07-31T17:00" step="1800">
<button type="submit">Book Appointment</button>
</form>
<p id="appointmentOutput"></p>
<script>
const appointmentForm = document.getElementById('appointmentForm');
const appointmentOutput = document.getElementById('appointmentOutput');
appointmentForm.addEventListener('submit', function(event) {
event.preventDefault();
const selectedTime = document.getElementById('appointmentTime').value;
appointmentOutput.textContent = 'Appointment Booked for: ' + selectedTime;
});
</script>
Output:
A user-friendly date and time picker is shown with a range of values between July 1 to July 31 of 2024, and between 9 am to 5 pm. Also the step value is 1800 seconds (30 minutes), allowing the user to select only time in 30 minute intervals. After filling the value, the selected value will be displayed on the page.
Browser Support
The datetime-local
input type is well-supported across modern browsers.
Note: Always test your web application on different browsers and devices to ensure a consistent and seamless experience for all users. 💻
Conclusion
The HTML DOM datetime-local
object and the <input type="datetime-local">
element are essential tools for web developers needing to capture date and time information from users. With the ability to set ranges, step intervals, and perform validation, you can create robust and user-friendly applications. This guide should serve as a comprehensive reference for accessing and manipulating these powerful input elements in your web development projects.
“`