Reputation: 1639
From an API I got 'times' and that 'times' I put into select box like:
<select id="time">
<option value="19:00:00">19:00:00</option>
<option value="20:00:00">20:00:00</option>
<option value="21:00:00">21:00:00</option>
<option value="22:00:00">22:00:00</option> /// ETC
</select>
I want to show 20:00:00 as default time so I simply write jquery code:
$('#time').val('20:00:00');
The problem is because API don't return me each time 20:00:00 as option so I need to choose some other time, so How I can select with jquery the closest time to 20:00:00 so etc. how to select 21:00:00 if 20:00:00 is not in select box ?
Upvotes: 0
Views: 229
Reputation: 24965
You could find all the options equal to or greater than the desired time, and then select the first one, provided the list is ordered already.
var time = '20:00:00';
function changeTime ( value ) {
//select all the options and filter them
$('#time option').filter(function(index, element){
//return just the ones that have a value equal to or
//greater than our desired time
return element.value >= value;
}).eq(0).prop('selected', true); //select the first one
}
changeTime( time );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="time">
<option value="19:00:00">19:00:00</option>
<option value="21:00:00">21:00:00</option>
<option value="22:00:00">22:00:00</option> /// ETC
</select>
Upvotes: 3