Page 1 of 1

Formatting / Padding Javascript output

Posted: Sun Dec 08, 2002 7:24 am
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.

Posted: Mon Dec 09, 2002 10:59 am
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.

Posted: Mon Dec 09, 2002 11:53 am
by f1nutter
Seems so obvious now! :oops:

Thanks.