The best script is at the bottom, looks a lot of code but can be altered to your requirements!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<SCRIPT> function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : event.keyCode; if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } </SCRIPT> <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar"> |
If you want to add decimal places add this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<script type="text/javascript"> // Restrict user input in a text field // create as many regular expressions here as you need: var digitsOnly = /[1234567890]/g; var integerOnly = /[0-9\.]/g; var alphaOnly = /[A-Za-z]/g; var usernameOnly = /[0-9A-Za-z\._-]/g; function restrictInput(myfield, e, restrictionType, checkdot){ if (!e) var e = window.event if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which; var character = String.fromCharCode(code); // if user pressed esc... remove focus from field... if (code==27) { this.blur(); return false; } // ignore if the user presses other keys // strange because code: 39 is the down key AND ' key... // and DEL also equals . if (!e.ctrlKey && code!=9 && code!=8 && code!=36 && code!=37 && code!=38 && (code!=39 || (code==39 && character=="'")) && code!=40) { if (character.match(restrictionType)) { if(checkdot == "checkdot"){ return !isNaN(myfield.value.toString() + character); } else { return true; } } else { return false; } } } </script> <!-- To accept only alphabets --> <input type="text" onkeypress="return restrictInput(this, event, alphaOnly);"> <!-- To accept only numbers without dot --> <input type="text" onkeypress="return restrictInput(this, event, digitsOnly);"> <!-- To accept only numbers and dot --> <input type="text" onkeypress="return restrictInput(this, event, integerOnly);"> <!-- To accept only numbers and only one dot --> <input type="text" onkeypress="return restrictInput(this, event, integerOnly, 'checkdot');"> <!-- To accept only characters for a username field --> <input type="text" onkeypress="return restrictInput(this, event, usernameOnly);"> |