Allows the user to enter a number with up to 2 decimal places in a text box. In other words, 99 is ok, 99.9 is ok, 99.99 is ok, but 99.999 is rejected. You can easily change the number of decimal places that are permitted. (i.e. 1, 2, 3, etc.) For the example, enter a number with up to 2 decimal places then try entering one with more than 2 decimal places.
Add the below code to the <body> section of your page:
<scriptlanguage="javascript"type="text/javascript"> /* Visit http://www.yaldex.com/
for full source code
and get more free JavaScript, CSS and DHTML scripts! */
<!-- Begin function
checkDecimals(fieldName,
fieldValue){
decallowed =2;// how many decimals are
allowed?
if(isNaN(fieldValue)||
fieldValue ==""){ alert("Oops!
That does not appear to be a valid number. Please try again."); fieldName.select(); fieldName.focus();
} else{ if(fieldValue.indexOf('.')==-1)
fieldValue +="."; dectext =
fieldValue.substring(fieldValue.indexOf('.')+1,
fieldValue.length);
if(dectext.length>
decallowed)
{ alert("Oops!
Please enter a number with up to "+
decallowed +" decimal places. Please try
again."); fieldName.select(); fieldName.focus(); } else{ alert("That
number validated successfully."); } }
} // End --> </script> <form> Please enter a number with up to 2
decimal places: <br> <inputtype=textname=numbox>
<input
type=buttonname=okvalue="Ok"onClick="checkDecimals(this.form.numbox,
this.form.numbox.value)">
</form>