View Full Version : Sequence Number
Leinad
03-19-2003, 01:01 AM
Hi all,
I need to use JavaScript to populate values like the following:
0001, 0002, 0003, 0004, 0005, 0006, 0007, 0008, 0009, 0010,
up to 9999.
is there an easy way to do this?
x_goose_x
03-19-2003, 01:17 AM
what exactly do you want this for?
val = 0;
val++;
increments it by one.
Jason
03-19-2003, 01:29 AM
does it need to have the leading zeros?
Jason
cheesebagpipe
03-19-2003, 01:33 AM
'populate values' is pretty vague. Did you mean 'populate an array'?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>untitled</title>
<script type="text/javascript" language="javascript">
var x = new Array(9999);
var zeros = '000';
for (var i=1; i<=9999; ++i) x[i] = zeros.substring(String(i).length - 1) + i;
alert('x[7] = ' + x[7]);
alert('x[55] = ' + x[55]);
alert('x[448] = ' + x[448]);
alert('x[909] = ' + x[909]);
alert('x[6823] = ' + x[6823]);
</script>
</head>
<body>
</body>
</html>
Slow as molasses, but it works. If you just need something to format numbers:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>untitled</title>
<script type="text/javascript" language="javascript">
Number.prototype.addLeadingZeros = function(strLength) {
var retStr = this.toString(), pad = strLength - retStr.length;
if (pad>0) while (pad--) retStr = '0' + retStr;
return retStr;
}
var x = 9;
alert(x.addLeadingZeros(4));
x = 99;
alert(x.addLeadingZeros(4));
x = 999;
alert(x.addLeadingZeros(4));
x = 9999;
alert(x.addLeadingZeros(4));
</script>
</head>
<body>
</body>
</html>
glenngv
03-19-2003, 07:02 AM
...or maybe, he wants something like this:
function addLeadingZeroes(num){
if (num<10) num="000"+num;
else if (num<100) num="00"+num;
else if (num<1000) num="0"+num;
return num;
}
alert(addLeadingZeroes(9));
alert(addLeadingZeroes(99));
alert(addLeadingZeroes(999));
alert(addLeadingZeroes(9999));
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.