I have a JavaScript question, and although this is a Java Forum, I'm sorry but I don't know where else to post this.
I have a form where a user enters a 3-digit number. The code takes the number and increments it by 1 as long as the number entered is not 999.
The problem is that if the number entered by the user is, for example, 023, the code increments the number to 24, which is right, but it drops the leading 0. It should increment the number to show 024.
Can someone please tell me how to fix this problem? My code is below:
function btn() { var num=document.frm.txt.value
if (num == 999) { alert("You have reached the maximum number of " + num) } else { num++ alert("The new number is " + num) } }
Sure would be nice if JavaScript had something like sprintf() (or the Python % string operator). Maybe it does have something like that; you might asking some real JavaScript gurus in the comp.lang.javascript newsgroup or on one of the many JavaScript web sites (see Google). Anyway, this little function will do the specific thing you are asking about:
function PadInt(i,width,pad)
{
if( i < 0 || (i + "").length >= width )
return i;
return PadInt(pad + i,width,pad);
}
// Here's how you might call it:
zeroFourFour = PadInt( 44, 3, "0" );