Sign Up Form

Sign Up

How to trigger event on input date select when value is unchanged?

720 421 point-admin
  • 0

When a date is chosen in an HTML input element, you can use JavaScript to alter events and wait for the input element’s focus in order to initiate an event even if the value stays the same.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Date Input Event</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>

<label for="dateInput">Select a date:</label>
<input type="date" id="dateInput">

<script src="script.js"></script>

</body>
</html>


HTML: There’s a basic date input field available.

 

/* Add any styles you need here */
body {
font-family: Arial, sans-serif;
}

label {
margin-right: 10px;
}


 


CSS: For improved visualization, basic styles have been added; you can adjust as necessary.
JavaScript: To ensure that the script executes after the DOM has fully loaded, a DOMContentLoaded event listener is used.

document.addEventListener('DOMContentLoaded', function() {
const dateInput = document.getElementById('dateInput');
let previousValue = dateInput.value;

dateInput.addEventListener('focus', function() {
previousValue = dateInput.value;
});

dateInput.addEventListener('change', function() {
if (dateInput.value === previousValue) {
console.log('Date reselected: ' + dateInput.value);
// Trigger any event or function here
}
previousValue = dateInput.value;
});

dateInput.addEventListener('input', function() {
if (dateInput.value === previousValue) {
console.log('Date input triggered: ' + dateInput.value);
// Trigger any event or function here
}
});
});


 


When the input gains focus, the focus event listener captures its initial value.
The change event listener logs a message or starts an event when it determines that the date has not been modified (i.e., the value has not changed).
An extra level of verification for all user input interaction that occurs is offered by the input event listener.

 

Leave a Reply

Your email address will not be published.