Javascript Dynamic Time Drop Down

2019-06-21 05:50发布

I'm not very good at Javascript Time manipulation.

Here is what I am trying to do: I have a UI that needs a end time drop down list. Its a finite set of times, essentially from 7:00 AM to 10:00 PM in 15 minute increments. I'm using jQuery and want to create on the fly a Select box that looks like this:

<select>
<option value="420">7:00 AM</option>
<option value="435">7:15 AM</option>
<option value="450">7:30 AM</option>
etc...
</select>

Anyone know how to do this in javascript/jQuery. I want to do something dynamic like this:

for(int i = 420; i<=1320; i+=15){
//use value of i to increment a date or something and create an option for the drop down... this is where I am stuck
}

1条回答
2楼-- · 2019-06-21 06:44

The following snippet should help you get the idea:

function populate(selector) {
    var select = $(selector);
    var hours, minutes, ampm;
    for(var i = 420; i <= 1320; i += 15){
        hours = Math.floor(i / 60);
        minutes = i % 60;
        if (minutes < 10){
            minutes = '0' + minutes; // adding leading zero
        }
        ampm = hours % 24 < 12 ? 'AM' : 'PM';
        hours = hours % 12;
        if (hours === 0){
            hours = 12;
        }
        select.append($('<option></option>')
            .attr('value', i)
            .text(hours + ':' + minutes + ' ' + ampm)); 
    }
}

populate('#timeSelect'); // use selector for your select
查看更多
登录 后发表回答