I have a select dropdown with times in 30 min intervals like
11:00 AM, 11:30 AM, 12:00 PM, 12:30 PM, 1:00 PM
beginning from 0:00 AM and ending with 11:30 PM
<select id='time'>
<option value="11:30 AM">11:30 AM</option>
<option value="12:00 PM">12:00 PM</option>
<option value="12:30 PM">12:30 PM</option>
<option value="1:00 PM">1:00 PM</option>
<option value="1:30 PM">1:30 PM</option>
<option value="2:00 PM">2:00 PM</option>
<option value="2:30 PM">2:30 PM</option>
<option value="3:00 PM">3:00 PM</option>
<option value="3:30 PM">3:30 PM</option>
<option value="4:00 PM">4:00 PM</option>
<option value="4:30 PM">4:30 PM</option>
</select>
$(document).ready(function(){
$('#time').val(.now()); // this wouldnt work it gives the current time which may be between 30 min
});
I want this select dropdown to default to rounded to nearest higher time based on current time.
For eg. if the current time is 10:46 AM then the selected value should 11:00 AM and if the current time is 10:31 AM should also default to 11:00 AM.
Any pointers on achieving this using jquery or with normal javascript.
Thanks
You could use the
Math.roundfunction to get the value to the nearest half hour:Construct a date object from this and get the time.
Here is a demonstration: http://jsfiddle.net/GsR6v/9/