Reputation: 21
I want the time input field on specific times, so that only times from 8 AM to 8 PM can be selected. Bookings booked for 8:01 PM onwards, till booked for 7:59 AM can't be selected. How can I make this custom time picker using JavaScript/Jquery?
<input name="booking-time" type="time" id="book_time">
Upvotes: 1
Views: 3168
Reputation: 1799
Although I am a fan of native (browser only) controls, date (and time pickers) are difficult to handle cross-browser wise. Therefore it is best to use an existing library and to find out what your requirements are exactly.
There are lengthy articles on the topic, it would not make sense to copy them here, therefore I'd like to redirect you there.
UX/Usablity of date/time pickers:
I personally like to use flatpickr.
Upvotes: 1
Reputation: 1364
To pick times within a required range, you can add a min and max:
function show() {
let t = document.getElementById("book_time");
console.log(t.value);
}
function show2() {
let t2 = document.getElementById("book_time2");
let t2Hour = t2.value.substr(0, 2);
let t2Minute = t2.value.substr(3, 2);
if (t2.value.substr(0, 2) < t2.min) {
alert("Earliest time is " + t2.min);
t2.value = t2.min;
} else if (t2.value.substr(0, 2) > t2.max){
alert("Latest time is " + t2.max);
t2.value = t2.max;
} else {
console.log(t2.value);
}
}
#book_time::after {
content: "___";
position: relative;
left: -20px;
line-height:1.5em;
background-color: white;
color: white;
}
<input type="time" id="book_time" name="booking-time" min="08:00" max="20:00" required onchange="show();">
<input type="time" id="book_time2" name="booking-time2" min="08:00" max="20:00" required onchange="show2();">
UPDATE
There does seem to be a browser issue. Some browsers will honour the min/max values, others don't. The ones that don't show a clock symbol to the right of the HH:MM display. The ones that do, show up/down arrows instead.
The updated snippet above offers two possible solutions.
The first one hides the clock symbol by covering it with a block of white text on a white background defined by the ::after pseudo-selector in a css style. The down-side is that there is nothing to tell the user what to do - they have to know to click in the hour part of the input and use their up/down arrow keys to change the hour value. Additionally, there will be whitespace at the right of the box that can not be removed.
The second one uses javascript to confirm that the hour selected falls within the allowable range. If they select anything outside of those hours, they get an alert and their time is set to either the min or max value as appropriate.
The only other solution would be to provide separate select lists for hours and minutes and restrict the range that way. That's not as elegent as a simple input box but does ensure that the user can not select an invalid value.
Upvotes: 2