You are here: irt.org | FAQ | JavaScript | Number | Q332 [ previous next ]
You can do is run some JavaScript code when the user leaves the text box.
Firstly, put the following in the HEAD section of your page:
<SCRIPT LANGUAGE="JAVASCRIPT"><!-- function check(contents) { if (((contents / contents) != 1) && (contents != 0)) {alert('Please enter only a number into this text box')} } //--></SCRIPT>
Then your text box line should be similar to this one:
<INPUT TYPE=TEXT SIZE=20 NAME="text1" onBlur="check(this.value)">
You can re-use the same bit over and over for different text boxes.
If you are interested in how this works I'll explain. First of all, we take the value of the text box and divide it by itself. If a number has been entered, the result should be equal to 1, unless 0 was entered. If text has been entered, the result will be something different (usually NaN for Not a Number). Therefore, if the result is not equal to 1 and the number entered is not equal to 0, then an error message is displayed. Obviously you can change the nature of the error message to whatever you want, or specify that some other action should take place.