How to clear DateRangePicker value in JavaScript?
The DateRangePicker component is a versatile tool for selecting a range of dates in web applications. However, there may be instances where you need to clear the selected date range programmatically. This article outlines the steps to achieve this using JavaScript.
Steps to Clear DateRangePicker Value
-
Access the DateRangePicker Instance: First, ensure you have a reference to the DateRangePicker instance. This can typically be done by using the ID of the DateRangePicker element.
var dateRangePicker = document.getElementById('dateRangePicker').ej2_instances[0];
-
Clear the Value: Use the
value
property of the DateRangePicker instance to set it tonull
or an empty array, depending on the implementation.dateRangePicker.value = null; // or dateRangePicker.value = [];
-
Refresh the Component: After clearing the value, it may be necessary to refresh the DateRangePicker to reflect the changes in the UI.
dateRangePicker.dataBind();
Example Code
Here is a complete example demonstrating how to clear the DateRangePicker value:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DateRangePicker Example</title>
<link href="https://cdn.syncfusion.com/ej2/19.1.55/material.css" rel="stylesheet">
<script src="https://cdn.syncfusion.com/ej2/19.1.55/dist/ej2.min.js"></script>
</head>
<body>
<input type="text" id="dateRangePicker" />
<button id="clearButton">Clear Date Range</button>
<script>
var dateRangePicker = new ej.calendars.DateRangePicker({
placeholder: 'Select a range',
format: 'MM/dd/yyyy'
});
dateRangePicker.appendTo('#dateRangePicker');
document.getElementById('clearButton').onclick = function() {
dateRangePicker.value = null; // Clear the value
dateRangePicker.dataBind(); // Refresh the component
};
</script>
</body>
</html>