简体   繁体   English

如何制作选择下拉列表以根据当前时间选择选项值

[英]How make a select dropdown to select an option value based on current time

I have a select dropdown with times in 30 min intervals like我有一个选择下拉列表,时间间隔为 30 分钟,例如

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从 0:00 AM 开始到 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.如果当前时间是上午 10:46,则选择的值应该是上午 11:00,如果当前时间是上午 10:31,也应该默认为上午 11:00。

Any pointers on achieving this using jquery or with normal javascript.关于使用 jquery 或普通 javascript 实现这一点的任何指针。

Thanks谢谢

You could use the Math.round function to get the value to the nearest half hour:您可以使用Math.round函数将值获取到最接近的半小时:

Math.round(Date.now()/(30*60*1000))*(30*60*1000));

Construct a date object from this and get the time.从中构造一个日期对象并获取时间。

var date = new Date(Math.round(Date.now() / (30 * 60 * 1000)) * (30 * 60 * 1000));
$('#time').val(date.getHours()%12 + ":" + ("0"+date.getMinutes()).slice(-2) + " " + (date.getHours() >= 12 ? "PM" : "AM"));

Here is a demonstration: http://jsfiddle.net/GsR6v/9/这是一个演示: http : //jsfiddle.net/GsR6v/9/

You can try to round the value of the Date something like this:您可以尝试将 Date 的值四舍五入,如下所示:

var date = new Date(Math.round(Date.now()/(30*60*1000))*(30*60*1000));

Then use this to set up the date:然后使用它来设置日期:

$("select option").filter(function() {
  //may want to use $.trim in here
  return $(this).text() == <YourDate>; 
}).attr('selected', true);​

Try this on my fiddle: http://jsfiddle.net/mC869/在我的小提琴上试试这个: http : //jsfiddle.net/mC869/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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