Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Dynamic Time Drop Down

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
}
like image 755
Matt Avatar asked Jan 18 '12 22:01

Matt


1 Answers

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
like image 115
Li0liQ Avatar answered Sep 30 '22 10:09

Li0liQ