Generate a hour:minute select list

11,208

You can use a simple for-loop to generate it in javascript (or PHP/Ruby if you would like, the basic structure is the same).

Such as:

var selection = "";
var i = 0;
for(var i = 0; i < 24; i++)
{
    selection += "<option value='"+ zeroFill(i, 2) +"00'>"+ zeroFill(i, 2) + ":00" + "</option>";
        selection += "<option value='"+ zeroFill(i, 2) +"30'>"+ zeroFill(i, 2) + ":30" + "</option>";
}
$("select").html(selection);

function zeroFill( number, width )
{
  width -= number.toString().length;
  if ( width > 0 )
  {
    return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
  }
  return number + ""; // always return a string
}

Here is an example: http://jsfiddle.net/MrXenotype/chafg/

The ZeroFill function is taken from here: How can I pad a value with leading zeros?

It adds leading 0s to the numbers.

Share:
11,208
Alex
Author by

Alex

I'm a .net developer from Camberley, Surrey. Strong interest in web applications - emphasis on back end APIs. Recently working in serverless applications. Enjoy speaking at tech events where possible.

Updated on June 26, 2022

Comments

  • Alex
    Alex almost 2 years

    Is there a way to generate something like the following markup:

    <select> 
        <option value="0000">00:00</option>
        <option value="0030">00:30</option>
        <option value="0100">01:00</option>
        <option value="0130">01:30</option>
        <option value="0200">02:00</option>
        <option value="0230">02:30</option>
        <option value="0300">03:00</option>
        <!--rest of options omitted for brevity-->
    </select>
    

    ... all the way up to 23:30 - so repeating every 30 minutes?

    I'm using rails 3, and while this works, it doesn't include the minutes (in my case, every half hour)

    select_hour(13, :prompt => 'Choose hour')
    
    • Sikshya Maharjan
      Sikshya Maharjan over 11 years
      Do you need this to be server-side (which would make more sense), in Ruby, or would client-side in JavaScript be okay?
    • Alex
      Alex over 11 years
      either- the js answer provided looks good, was just wondering if there was a one-liner rails helper i could use (it seems not though)