简体   繁体   中英

Select closest value in select box with jquery

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 ?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM