Last Updated on April 1, 2024 by Roshan Parihar
If you want to display an alert at the specified date and time, you have to use the Date()
and getTime()
It also requires using of the setTimeout()
function and passing the specified date and time as its argument.
How to Display Alert at the Specified Date and Time
First, create a form with the input as date and time to be specified by the users. You can use the <input type="datetime-local">
type of the form element to get the user’s datetime input. See the date and time input in the added form.
1 2 3 4 |
<form method="post"> <input type="datetime-local" class="form-control" placeholder="Enter date and time" name="reminder_date_time" id="reminder_date_time" required> <input type="submit" name="submit" value="Submit" id="form_submit"> </form> |
Now, to display the alert at the specified date and time, you have to use the jQuery script as given below. Add the jQuery library with the library URL. After that, get the input date and time value of the form on the button click.
The below script matches the specified date and the current date. The specified date should be greater than the current date to display the alert.
You have to find the difference between the current date and the specified date. It should only display the alert when the difference between the specified and current dates is greater than zero. See the example given below to learn the method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<script type="text/javascript"> $(document).ready(function(){ $('#form_submit').click(function(){ var mydatetime = $('#reminder_date_time').val(); var alertDate = new Date(mydatetime).getTime(); onloadDate = Date.now(); tOut = alertDate - onloadDate; if(tOut > 0){ setTimeout(()=>{ alert("Hello"); }, tOut ); } return false; }); }); </script> <form method="post"> <input type="datetime-local" class="form-control" placeholder="Enter date and time" name="reminder_date_time" id="reminder_date_time" required> <input type="submit" name="submit" value="Submit" id="form_submit"> </form> |
You can check the live example with the ‘Test it Live’ button given above. In the test live example, select the date and time when you want to display the alert. After that, click the submit button and wait until you reach your date-time. You will get an alert at your specified date and time.
So, this a simple example but useful when you want to display alerts to your audience.
You May Also Like to Read