Issue
Is it possible to disable the options after it goes out the range of time just by using HTML and JavaScript?
<select onchange="myFunction()">
<option value="" disabled selected>Select delivery time</option>
<option value="10">10.00 AM - 12.00 PM</option>
<option value="1">1.00 PM - 3.00 PM</option>
<option value="3">3.00 PM - 7.00 PM</option>
</select>
<script>
function myFunction(){
const b = new Date();
let hours = b.getHours();
if(hours < document.getElementById('time1').value){
document.select.options[1].disabled = true;
}
}
</script>
Solution
Instead of calling the function at onChange
event, call at document load or when document is ready.
For this particular need, is better approach if you have your intervals in options values, I used an interval like this value="10-11"
it represents 10am to 11am.
If you use getHours()
method, it returns the hours in military time based means that for 10pm it will return 22.
let element = document.getElementById('time1');
let validateInterval = (element) => {
let currentDate = new Date();
let currentHour = currentDate.getHours();
for (let opt of element.options) {
let timeOpt = opt.value.split('-');
if (Array.isArray(timeOpt) && timeOpt.length > 1) {
opt.disabled = (+timeOpt[0] <= currentHour && +timeOpt[1] > currentHour) ? false : true;
}
}
}
validateInterval(element);
<select id="time1">
<option value="" disabled selected>Select delivery time</option>
<option value="10-12">10:00 AM - 12:00 PM</option>
<option value="13-15">1:00 PM - 3:00 PM</option>
<option value="15-19">3:00 PM - 7:00 PM</option>
<option value="20-22">8:00 PM - 10:00 PM</option>
<option value="21-23">9:00 PM - 11:00 PM</option>
<option value="22-23">10:00 PM - 11:00 PM</option>
</select>
From this, you can add minutes intervals too, go ahead an try by yourself.
Answered By - Elvis Pimentel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.