0

How to restrict my text field to numbers only and limit them in two with a single function.

theJava
  • 14,620
  • 45
  • 131
  • 172
  • 3
    What do you mean "limit them in two" ? – mplungjan Apr 07 '11 at 08:26
  • 2
    What do you have so far? – Kobi Apr 07 '11 at 08:27
  • 1
    Text fields have a "maxsize" attribute, no JS needed. Check google for "textfield limit numbers" for a gazillion tutorials. –  Apr 07 '11 at 08:28
  • http://stackoverflow.com/questions/995183/how-to-allow-only-numeric-0-9-in-html-inputbox-using-jquery – Amr Elgarhy Apr 07 '11 at 08:29
  • 1
    Perhaps the OP wants to dynamically change the maximum number of characters allowed in a field. I could conceive of a use for this. – Oren Hizkiya Apr 07 '11 at 08:36
  • Oren you got me... thanks i did not indite that one – theJava Apr 07 '11 at 08:37
  • @theJava -- There seems to be a lot of different interpreations being made of what you want. Perhaps you could edit the question to make it more clear exactly what you're trying to achieve. You may get more helpful answers. – Spudley Apr 07 '11 at 08:57

5 Answers5

2

For limiting them to enter only 2 char use maxlength attribute of input. To check enter string is number or not user isNaN(str) function.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
2

Since no one has suggested a regular expression, I will. :-)

var re = /^-?\d{1,2}$/;
if (re.test(input.value)) {
  // number is one or two digits with optional leading minus
} else {
  // it's not
}
RobG
  • 142,382
  • 31
  • 172
  • 209
1
<script type="text/javascript">
    function ValidateField(FieldName){

        // Get fields value
        var FieldVal = document.GetElementById(FieldName).value;

        // Check it's a number, and then check it's range is correct
        // Alternatively you could do FieldVal.length
        if(!isNaN(FieldVal) && (FieldVal < 100 && FieldVal > -100))
            alert("Valid!");
        else
            alert("Invalid");
    }
</script>    

<input type="text" name="MyField" />
<button onclick="ValidateField('MyField')">Test</button>

I've interpreted 'limit to 2' to mean a number ranging from -99 to 99.

okm
  • 23,575
  • 5
  • 83
  • 90
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456
1

In HTML5 you can just use: <input type="number" />

Corneliu
  • 2,932
  • 1
  • 19
  • 22
1

If you are using jquery:

$('#myTextAreaID').keydown(function(event) {
  if (event.target.length >1 || event.keyCode < 48 || event.keyCode > 57) {
     event.preventDefault();
   }
});

if you want it to work with the numeric keypad, you will need to also allow keycodes 96 to 105

herostwist
  • 3,778
  • 1
  • 26
  • 34
  • thinking further this may be better: event.target.length >1 || String.fromCharCode(event.keyCode).match(/\D/); – herostwist Apr 07 '11 at 09:47