[英]Pre-select time with a Select2 component
I'm new to JavaScript (from Flex). 我是JavaScript的新手(来自Flex)。 I'm using a Select2 component to show time of day in 15 minute increments:
我正在使用Select2组件以15分钟为增量显示一天中的时间:
<select id="e2" style="width:125px">
<option value="00:00:00">12:00 AM</option>
<option value="00:15:00">12:15 AM</option>
<option value="00:30:00">12:30 AM</option>
<option value="00:45:00">12:45 AM</option>
<option value="01:00:00">1:00 AM</option>
<option value="01:15:00">1:15 AM</option>
<option value="01:30:00">1:30 AM</option>
<option value="01:45:00">1:45 AM</option>
</select>
What I want is to pre-select the time that most closely matches the current time (in the future); 我想要的是预先选择与当前时间(将来)最接近的时间; for example, if it's 12:02 now, I want 12:15 selected (not 12:00).
例如,如果现在是12:02,我希望选择12:15(而不是12:00)。
My question is how and where to do that using Select2. 我的问题是使用Select2的方式和位置。
Do I use the "init selection" method when I initialize the component: 初始化组件时是否使用“初始选择”方法:
$( '#e2' ).select2();
Or is it better to do something else? 还是做其他事情更好?
Here's the current method I use (in Flex) to set the date. 这是我在Flex中使用的当前方法来设置日期。 I'm just a little unsure of where to do this with a Select2 component.
我只是不确定在哪里使用Select2组件执行此操作。
Any tips are greatly appreciated. 任何提示,不胜感激。 Thank you!
谢谢!
For what you need to achieve, I would say the best way is to create your own function to find the closest time slot and then format the string to match your Select option values. 对于您需要实现的目标,我想说最好的方法是创建自己的函数以找到最接近的时隙,然后格式化字符串以使其与Select选项值匹配。
Below is the sample code (you need to format it as you need) but it works for me for current time here: 以下是示例代码(您需要根据需要设置其格式),但在这里,它对我当前有效:
Sample: http://jsfiddle.net/ZC5tG/ 范例: http : //jsfiddle.net/ZC5tG/
HTML HTML
<select id="e2" style="width:125px">
<option value="12:00:00">12:00 AM</option>
<option value="12:15:00">12:15 AM</option>
<option value="12:30:00">12:30 AM</option>
<option value="12:45:00">12:45 AM</option>
<option value="01:00:00">1:00 AM</option>
<option value="01:15:00">1:15 AM</option>
<option value="01:30:00">1:30 AM</option>
<option value="01:45:00">1:45 AM</option>
</select>
jQuery jQuery的
<script>
function getNearestTimeSlotString() {
var now = new Date();
var hour = now.getHours();
var minutes = now.getMinutes();
var ampm = "AM";
if (minutes < 15) {
minutes = "00";
} else if (minutes < 30){
minutes = "15";
}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 + ":00");
}
$(document).ready(function(e) {
alert(getNearestTimeSlotString());
$("#e2").val(getNearestTimeSlotString);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.