Formatting / Padding Javascript output

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
f1nutter
Forum Contributor
Posts: 125
Joined: Wed Jun 05, 2002 12:08 pm
Location: London

Formatting / Padding Javascript output

Post by f1nutter »

Hi,

I am designing a form for a competition on my site. It involves guessing lap times for a race. I have three SELECT options, one for guessing the minute, one for the seconds, and one for fractions of a second. I am using JavaScript to write the option values, from 0-59 for the seconds, but I want it to display leading zero's, so 00, 01, ... 09, 10 etc. and three places for the fractions, 000 .. 009 .. 099, 100 etc.

This is what I have. The option value doesn't need padding, but the displayed value does to reduce confusion.

Code: Select all

<select name="s">
 <script type="text/javascript">
  <!--
   for (i = 0 ; i < 60 ; i++)
   &#123;
    document.write('<option value=' + i + '>' + i + '</option>');
   &#125;
  //-->
 </script>
</select>
Thanks.
Rob the R
Forum Contributor
Posts: 128
Joined: Wed Nov 06, 2002 2:25 pm
Location: Houston

Post by Rob the R »

Try this:

Code: Select all

<select name="s"> 
<script type="text/javascript"> 
<!-- 
for (i = 0 ; i < 60 ; i++) 
&#123; 
   if (i < 10) &#123; i = "0" + i ; &#125;
   document.write('<option value=' + i + '>' + i + '</option>'); 
&#125; 
//--> 
</script> 
</select>
You could put this in a Javascript function so you can pass the number and the field width so that you don't have to have a separate "if" statement for each select item and each leading zero to be added.
f1nutter
Forum Contributor
Posts: 125
Joined: Wed Jun 05, 2002 12:08 pm
Location: London

Post by f1nutter »

Seems so obvious now! :oops:

Thanks.
Post Reply