Here, a function is used to convert the current time to the next half hour in the form used in your parameters (for example, the nearest time is "10:30 PM"), and then a way to use this time to select the desired option.
function getNearestHalfHourTimeString() { var now = new Date(); var hour = now.getHours(); var minutes = now.getMinutes(); var ampm = "AM"; if (minutes < 15) { minutes = "00"; } else if (minutes < 45){ minutes = "30"; } else { minutes = "00"; ++hour; } if (hour > 23) { hour = 12; } else if (hour > 12) { hour = hour - 12; ampm = "PM"; } else if (hour == 12) { ampm = "PM"; } else if (hour == 0) { hour = 12; } return(hour + ":" + minutes + " " + ampm); }
You can choose your preferred option:
// remove any previous selection $('#select-choice-etime option').removeAttr('selected'); // select the one that matches the current time $('#select-choice-etime option[value="' + getNearestHalfHourTimeString() + '"]').attr('selected', 'selected');β
You can see how it works here: http://jsfiddle.net/jfriend00/Zz7pW/
source share