# Posted By

blackf0rk on 03/12/09

# Statistics

Viewed 1227 times
Favorited by 0 user(s)

# Limit text input to numbers (with or without decimals)

/ Published in: JavaScript

Copy this code and paste it in your HTML
1. // Limit the text field to only numbers (with decimals)
2. function format(input){
3. var num = input.value.replace(/\,/g,'');
4. if(!isNaN(num)){
5. if(num.indexOf('.') > -1){
6. num = num.split('.');
7. num[0] = num[0].toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'\$1,').split('').reverse().join('').replace(/^[\,]/,'');
8. if(num[1].length > 2){
9. alert('You may only enter two decimals!');
10. num[1] = num[1].substring(0,num[1].length-1);
11. } input.value = num[0]+'.'+num[1];
12. } else {
13. input.value = num.toString().split('').reverse().join('').replace(/(?=\d*\.?)(\d{3})/g,'\$1,').split('').reverse().join('').replace(/^[\,]/,'') };
14. } else {
15. alert('You may enter only numbers in this field!');
16. input.value = input.value.substring(0,input.value.length-1);
17. }
18. }
19.
20. // Limit the text field to only numbers (no decimals)
21.
22. function formatInt(input){
23. var num = input.value.replace(/\,/g,'');
24. if(!isNaN(num)){
25. if(num.indexOf('.') > -1) {
26. alert("You may not enter any decimals.");
27. input.value = input.value.substring(0,input.value.length-1);
28. }
29. } else {
30. alert('You may enter only numbers in this field!');
31. input.value = input.value.substring(0,input.value.length-1);
32. }
33. }
34.
35.
36. //utilization
37. <input id="text" name="text" size="5" onkeyup="format(this);">