Any quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes(plus '.')?

share|improve this question
53  
Many solutions here only work when keys are pressed. These will fail if people paste text using the menu, or if they drag and drop text into the text input. I've been bitten by that before. Be careful! – Bennett McElwee Jan 24 '11 at 21:09
51  
@JuliusA - you always always need server-side validation anyway. – Stephen P Nov 23 '11 at 1:57
27  
<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input> – Droogans Jan 20 '13 at 20:13
11  
@Droogans notice that also disables any other key, like TAB to go to the next input or any other shortcut not directly involved with input like cmd+R for refreshing the website if the input is focused. – Alejandro Pérez Nov 5 '13 at 9:54
1  
If you are okay with Plugin, use NumericInput. Demo: jsfiddle.net/152sumxu/2 More details here stackoverflow.com/a/27561763/82961 – Faiz Dec 19 '14 at 7:53

49 Answers 49

up vote 494 down vote accepted

JavaScript (the most reliable still)

<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'></input>

While this is simple, it will not let you use combination keys and other non typeable keys. For a more complete JavaScript solution that also supports input of type number and max length validation, consider using this Polyfill.

HTML 5 (does not require JavaScript, and also does not behave in standard way in many modern browsers.)

<input type="number">

Try input type=number to see the HTML5 version in action.

jQuery

$(document).ready(function() {
    $("#txtboxToFilter").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) ||
             // Allow: Ctrl+C
            (e.keyCode == 67 && e.ctrlKey === true) ||
             // Allow: Ctrl+X
            (e.keyCode == 88 && e.ctrlKey === true) ||
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});

More complex validation options

If you want to do some other validation bits and pieces, this could be handy:

http://www.javascript-coder.com/html-form/javascript-form-validation.phtml https://github.com/lockevn/html-numeric-input

But don't forget you still must do server side validation!

for AZERTY keyboard:

jQuery

// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
    // Allow: Ctrl+A
    (e.keyCode == 65 && e.ctrlKey === true) ||
    // Allow: Ctrl+C
    (e.keyCode == 67 && e.ctrlKey === true) ||
    // Allow: Ctrl+X
    (e.keyCode == 88 && e.ctrlKey === true) ||
    // Allow: home, end, left, right
    (e.keyCode >= 35 && e.keyCode <= 39) ||
    //Allow numbers and numbers + shift key
    ((e.shiftKey && (e.keyCode >= 48 && e.keyCode <= 57)) || (e.keyCode >= 96 && e.keyCode <= 105))) {
    // let it happen, don't do anything
    return;
}
// Ensure that it is a number and stop the keypress
if ((!e.shiftKey && (e.keyCode < 48 || e.keyCode > 57)) || (e.keyCode < 96 || e.keyCode > 105)) {
    e.preventDefault();
}
share|improve this answer
3  
Although this would be a good choice, this still allows to enter characters like /, multiple dots, other operators etc. – Mahendra Mar 12 '13 at 19:36
3  
Still not supported by Firefox 21 (I don't even talk about IE9 or earlier version ...) – JBE May 24 '13 at 17:40
19  
The input type number is not meant to be used to make your input only accept numbers. It's meant for inputs which specify a 'number of items'. Chrome for example adds two small arrows to increase of decrease the number by one. A proper numberic-only input is a kind of ridiculous omission to HTML. – Erwin Jun 28 '13 at 8:45
7  
The type="number" does not actually prevent entering invalid text into the field; appears that you can even cut and paste garbage data into the field, even in chrome. – perfectionist Jun 13 '14 at 11:15
3  
The only thing I would add to this is to change the Ctrl+A line to include MacOSX users: (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) – MForMarlon Mar 17 '15 at 23:06

Use this DOM

<input type='text' onkeypress='validate(event)' />

And this script

function validate(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}
share|improve this answer
11  
german-settings on an eeepc 900. some key's for good usabiliy do not work: - backspace (keyCode: 8) - navigation key left and right (keyCode: 37, 38) copy and paste is also possible... – Michael Piendl Sep 10 '09 at 18:24
3  
change to if (theEvent.preventDefault) theEvent.preventDefault(); as it's not supported by all browsers – pstanton Oct 24 '09 at 1:25
8  
Most people do care, having a script error show up reflects poorly on your site. – Robert Jeppesen Apr 26 '10 at 21:37
10  
few problems with this code. You can enter . more than one time, second it does not allow delete key, any solution? – coure2011 May 16 '11 at 11:09
4  
I cared about backspace, delete and arrows not working. If you remove "theEvent.keycode ||", and add: "if( /[ -~]/ && !regex.test(key) ) {" then it does work better (for ASCII/UTF anyway). But then it won't reject chinese characters! :) – Sam Watkins Jun 3 '11 at 7:44

I've searched long and hard for a good answer to this, and we desperately need <input type="number", but short of that, these 2 are the most concise ways I could come up with:

<input type="text" 
       onkeyup="this.value=this.value.replace(/[^\d]/,'')">

If you dislike the non-accepted character showing for a split-second before being erased, the method below is my solution. Note the numerous additional conditions, this is to avoid disabling all sorts of navigation and hotkeys. If anyone knows how to compactify this, let us know!

<input type="text" 
onkeydown="return ( event.ctrlKey || event.altKey 
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false) 
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9) 
                    || (event.keyCode>34 && event.keyCode<40) 
                    || (event.keyCode==46) )">
share|improve this answer
2  
input type="number" is coming in HTML 5 - and you could use JavaScript as a fall-back polyfill... stevefenton.co.uk/Content/Blog/Date/201105/Blog/… – Sohnee May 23 '11 at 23:06
3  
Good method but can be broken by pressing and holding a non-acceptable key – Scott Brown Nov 16 '11 at 16:24
3  
Change the regex to /[^\d+]/ and it works with holding down – boecko Apr 24 '12 at 17:01
3  
@boecko thanks for this, but note that it should be /[^\d]+/ instead. Good solution though. Also @user235859 – Mosselman Jun 11 '12 at 21:49
6  
He wanted to allow . too. You should actually make it /[^0-9.]/g – Qsario Aug 1 '12 at 7:20

HTML5 has <input type=number>, which sounds right for you. Currently, only Opera supports it natively, but there is a project that has a JavaScript implementation.

share|improve this answer
    
Here's a document defining which browsers support this attribute: caniuse.com/input-number. As of the writing of this, Chrome and Safari both fully support this type field. IE 10 has partial support, and Firefox has no support. – Nathan Wallace Jul 25 '13 at 14:05
    
The only problem with type=number is that is not supported by IE9 – J Rod Jun 6 at 2:32
    
@JRod There's a polyfill for old IE. More info here. – jkdev Jul 7 at 8:40

And one more example, which works great for me:

function validateNumber(event) {
    var key = window.event ? event.keyCode : event.which;

    if (event.keyCode === 8 || event.keyCode === 46
     || event.keyCode === 37 || event.keyCode === 39) {
        return true;
    }
    else if ( key < 48 || key > 57 ) {
        return false;
    }
    else return true;
};

Also attach to keypress event

$(document).ready(function(){
    $('[id^=edit]').keypress(validateNumber);
});

And html:

<input type="input" id="edit1" value="0" size="5" maxlength="5" />

Update:

Here is jsfiddle example

share|improve this answer
    
What about pasted text? – Jason Ebersey Jun 6 '13 at 12:34
    
Why do I get "event is undefined" when I call this function? – Vincent Mar 6 '14 at 19:25
    
Are you calling validateNumber function on jQuery keypress? – vmaksym Mar 20 '14 at 14:34
    
this doesn't work on Firefox when the event.keyCode is always returned 0. I fixed with new code: function validateNumber(event) { var key = event.which || event.charCode || event.keyCode || 0; if (key == 8 || key == 46 || key == 37 || key == 39) { return true; } else if ( key < 48 || key > 57 ) { return false; } return true; }; – Luan Nguyen Nov 24 '15 at 22:41
    
It works as expected, event.keyCode returns code of arrow button key if it is pressed – vmaksym Nov 25 '15 at 8:47

I opted to use a combination of the two answers mentioned here i.e.

<input type="number" />

and

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    return !(charCode > 31 && (charCode < 48 || charCode > 57));
}

<input type="text" onkeypress="return isNumberKey(event);">

share|improve this answer
    
Excellent answer... +1. You can also reduce the if statement to: return !(charCode > 31 && (charCode < 48 || charCode > 57)); – schadeck Apr 2 '13 at 21:12
3  
How about deleting though? You want numbers but you probably want people to be able to correct them without refreshing the page... – bluemunch Feb 3 at 1:27

Most answers here all have the weakness of using key- events.

Many of the answers would limit your ability to do text selection with keyboard macros, copy+paste and more unwanted behavior, others seem to depend on specific jQuery plugins, which is killing flies with machineguns.

This simple solution seems to work best for me cross platform, regardless of input mechanism (keystroke, copy+paste, rightclick copy+paste, speech-to-text etc.). All text selection keyboard macros would still work, and it would even limit ones ability to set a non-numeric value by script.

function forceNumeric(){
    var $input = $(this);
    $input.val($input.val().replace(/[^\d]+/g,''));
}
$('body').on('propertychange input', 'input[type="number"]', forceNumeric);
share|improve this answer
    
jQuery 1.7+ needed. This is a more complete answer since it takes in account inputs via "copy". And it is also simpler! – Memochipan Jun 29 '15 at 15:30
    
An alternative regex: replace(/[^\d]+/g,'') Replace all non-digits with empty string. The "i" (case insensitive) modifier is not needed. – Memochipan Jun 29 '15 at 16:20
    
You are right, i is not needed for this :-) – EJTH Jun 30 '15 at 9:44
    
This should be on top, since "onkey" event handlers in a tag should not be propagated any more... – gpinkas Oct 13 '15 at 12:12
    
This one is definitely the best answer here but it doesn't allow digits with decimal numbers. Any idea how that could work? – Atirag 9 hours ago

HTML5 supports regexes, so you could use this:

<input id="numbersOnly" pattern="[0-9.]+" type="text">

Warning: Some browsers don't support this yet.

share|improve this answer
5  
HTML5 also has <input type=number>. – Mathias Bynens Oct 18 '11 at 9:30
    
True. You should make this an answer. Ooops, @Ms2ger already has. – james.garriss Dec 1 '11 at 15:59
    
The <input type=number> adds arrows for increasing and decreasing in certain browsers so this seems like a good solution when we want to avoid the spinner – Ayrad May 7 '13 at 17:06
10  
Pattern only gets checked on submit. You can still enter letters. – Erwin Jun 28 '13 at 9:01
    
not supported by safari – Ravi Gadhia Dec 4 '13 at 10:44

so simple.... // In Javascript Function (can use HTML or PHP).

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

In Your Form Input :

<input type=text name=form_number size=20 maxlength=12 onkeypress='return isNumberKey(event)'>

With input max. (these above, is allow for 12 Digit number)

share|improve this answer
    
Great!! It works in IE and other browsers – Ramesh Sangili Feb 4 '13 at 23:01
    
Don't do that ! This blocks everything, numpad, arrow keys, Delete key, shortcuts (CTRL + A, CTRL + R for example), even the TAB key it's REALY anoying ! – Korri Feb 22 '13 at 21:56
    
@Korri I dont follow, what seems to be the problme? It did work fine in my case. – uneakharsh Mar 28 '13 at 12:21
    
first line must changed to : var charCode = (evt.which) ? evt.which : evt.keyCode; – peiman F. Jul 17 '14 at 22:35

2 solutions:

Use a form validator (for example with jQuery validation plugin)

Do a check during the onblur (i.e. when the user leaves the field) event of the input field, with the regular expression:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

<input type="text" ... onblur="testField(this);"/>
share|improve this answer
1  
Escape . with \. – AnthonyWJones Jan 22 '09 at 16:12
    
Interestingly, I had to give the regex is "^\\d\\.?\\d*$", but that might be because the page is run through an XSLT transform. – Paul Tomblin Apr 22 '10 at 15:04

JavaScript

function validateNumber(evt) {
    var e = evt || window.event;
    var key = e.keyCode || e.which;

    if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
    // numbers   
    key >= 48 && key <= 57 ||
    // Numeric keypad
    key >= 96 && key <= 105 ||
    // Backspace and Tab and Enter
    key == 8 || key == 9 || key == 13 ||
    // Home and End
    key == 35 || key == 36 ||
    // left and right arrows
    key == 37 || key == 39 ||
    // Del and Ins
    key == 46 || key == 45) {
        // input is VALID
    }
    else {
        // input is INVALID
        e.returnValue = false;
        if (e.preventDefault) e.preventDefault();
    }
}

additional you could add comma, period and minus (,.-)

  // comma, period and minus, . on keypad
  key == 190 || key == 188 || key == 109 || key == 110 ||

HTML

<input type="text" onkeydown="validateNumber(event);"/ >
share|improve this answer
    
Does not function correctly on keyboards where one has to use the shift key to enter a number (e.g. European AZERTY keyboard). – Diego Deberdt May 17 '13 at 7:43
    
thanks man, you really understand a question! Nice example and off course handling . or , (which most people do want if they work with numbers) – real_yggdrasil Jan 12 '15 at 9:15
    
This is the only one that works that prevent pasting non numeric values. – DEREK LEE Jan 11 at 15:18

If you want to suggest to the device(maybe a mobile phone) between alpha or numeric you can use <input type="number">

share|improve this answer

A short and sweet implementation using jQuery and replace() instead of looking at event.keyCode or event.which:

$('input.numeric').live('keyup', function(e) {
  $(this).val($(this).val().replace(/[^0-9]/g, ''));
});

Only small side effect that the typed letter appears momentarily and CTRL/CMD + A seems to behave a bit strange.

share|improve this answer

if you just want to only allow numbers 0-9 on a input, you can just remove all non numeric characters, without messing about charCodes and arrows ctrl and others kinds of keyboars, and this fix a string pasted or draged to a input.

this have a advantage that you don't have to worry about browser messy of keyEvents. you can use this to allow letters and -,. but this cant deal with valid numbers like (0.1.4- is not a integer nor float), in this case this others guys solutions is better.

LIVE DEMO

<input type="text" id="number" size="100" value="type a number here">

Javascript

addEvent(document.getElementById('number'),'keyup',validate);
addEvent(document.getElementById('number'),'mouseover',validate);

function validate(event){   
    var charsAllowed="0123456789";
    var allowed;
    for(var i=0;i<this.value.length;i++){       
        allowed=false;
        for(var j=0;j<charsAllowed.length;j++){
            if( this.value.charAt(i)==charsAllowed.charAt(j) ){ allowed=true; }
        }
        if(allowed==false){ this.value = this.value.replace(this.value.charAt(i),""); i--; }
    }
    return true;
}

yes, regex is less work but not faster than this.

share|improve this answer
<input name="amount" type="text" value="Only number in here"/> 

<script>
    $('input[name=amount]').keyup(function(){
        $(this).val($(this).val().replace(/[^\d]/,''));
    });
</script>
share|improve this answer
<input id="numbers" pattern="[0-9.]+" type="number">

you can use pattern for this. here you can see the complete mobile website interface tips

share|improve this answer

input type="number" is html5 attribute.

In other case this will help you.

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

<input type="number" name="somecode" onkeypress="return isNumberKey(event)"/>
share|improve this answer
    
first line must changed to : var charCode = (evt.which) ? evt.which : evt.keyCode; – peiman F. Jul 17 '14 at 22:35

Just an other variant with jQuery using

$(".numeric").keypress(function() {
    return (/\d/.test(String.fromCharCode(event.which) ))
});
share|improve this answer

This is the extended version of geowa4's solution. Supports min and max attributes. If the number is out of range, the previous value will be shown.

You can test it here.

Usage: <input type=text class='number' maxlength=3 min=1 max=500>

function number(e) {
var theEvent = e || window.event;
var key = theEvent.keyCode || theEvent.which;
if(key!=13&&key!=9){//allow enter and tab
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key)) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
    }   
  }
}

$(document).ready(function(){
    $("input[type=text]").filter(".number,.NUMBER").on({
        "focus":function(e){
         $(e.target).data('oldValue',$(e.target).val());
            },
        "keypress":function(e){
                e.target.oldvalue = e.target.value;
                number(e);
            },
        "change":function(e){
            var t = e.target;
            var min = $(t).attr("min");
            var max = $(t).attr("max");
            var val = parseInt($(t).val(),10);          
            if( val<min || max<val)
                {
                    alert("Error!");
                    $(t).val($(t).data('oldValue'));
                }

            }       
    });     
});

If the inputs are dynamic use this:

$(document).ready(function(){
    $("body").on("focus","input[type=text].number,.NUMBER",function(e){
        $(e.target).data('oldValue',$(e.target).val());
    }); 
    $("body").on("keypress","input[type=text].number,.NUMBER",function(e){
        e.target.oldvalue = e.target.value;
        number(e);
    }); 
    $("body").on("change","input[type=text].number,.NUMBER",function(e){
        var t = e.target
        var min = $(t).attr("min");
        var max = $(t).attr("max");
        var val = parseInt($(t).val());         
        if( val<min || max<val)
            {
                alert("Error!");
                $(t).val($(t).data('oldValue'));
            }
    }); 
});
share|improve this answer
    
it doesn't delete :) – Sedz Jul 18 '12 at 23:33
    
@UserB this should not delete anything. – user669677 Jul 19 '12 at 11:14

Lots of great answers here but thought I'd contribute this simple one which allows for exactly one decimal but no more:

<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" />
share|improve this answer

this is an improved function :

function validateNumber(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
  }
}
share|improve this answer

You can also compare input value (which is treated as string by default) to itself forced as numeric, like:

if(event.target.value == event.target.value * 1) {
    // returns true if input value is numeric string
}

However, you need to bind that to event like keyup etc.

share|improve this answer

You can replace the Shurok function with:

$(".numeric").keypress(function() {
    return (/[0123456789,.]/.test(String.fromCharCode(Event.which) ))
});
share|improve this answer

Javascript code:

function validate(evt)

 {

  if(evt.keyCode!=8)

  {

  var theEvent = evt || window.event;

  var key = theEvent.keyCode || theEvent.which;

  key = String.fromCharCode( key );


  var regex = /[0-9]|\./;

  if( !regex.test(key) )
 {

    theEvent.returnValue = false;

    if(theEvent.preventDefault) theEvent.preventDefault();

  }

  }

}

HTML code:

<input type='text' name='price' value='0' onkeypress='validate(event)'/>

works perfectly because backspace keycode is 8 and regex expression doesnt let it so its a easy way to bypass the bug :)

share|improve this answer

The best way (allow ALL type of numbers - real negative, real positive, iinteger negative, integer positive) is:

$(input).keypress(function (evt){
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[-\d\.]/; // dowolna liczba (+- ,.) :)
    var objRegex = /^-?\d*[\.]?\d*$/;
    var val = $(evt.target).val();
    if(!regex.test(key) || !objRegex.test(val+key) || 
            !theEvent.keyCode == 46 || !theEvent.keyCode == 8) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
    };
}); 
share|improve this answer
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Allow Only Numbers
</HEAD>

<BODY>
<script language="JavaScript">
function onlyNumbers(evt)
{
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;

if (charCode > 31 && (charCode < 48 || charCode > 57))
    return false;

return true;

}
</script>
<input type="text" onkeypress="return onlyNumbers();">
</BODY>
</HTML>
share|improve this answer
    
COPY PASTE from other answer : Don't do that ! This blocks everything, numpad, arrow keys, Delete key, shortcuts (CTRL + A, CTRL + R for example), even the TAB key it's REALY anoying ! – Korri Feb 22 '13 at 22:02

another easy way with jquery:

     $('.Numeric').bind('keydown',function(e){
             if (e.which < 48 ||  e.which > 57)
                return false;
                return true;
       })           

now just set your each inputs class to Numeric, like:

     <input type="text" id="inp2" name="inp2" class='Numeric' />
share|improve this answer
    
COPY PASTE from other answer : Don't do that ! This blocks everything, numpad, arrow keys, Delete key, shortcuts (CTRL + A, CTRL + R for example), even the TAB key it's REALY anoying ! – Korri Feb 22 '13 at 22:01

How about this DOM...

<input type = "text" onkeydown = "validate(event)"/>

...and this script?

validate = function(evt)
{
    if ([8, 46, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36].indexOf(evt.keyCode || evt.which) == -1)
    {
        evt.returnValue = false;
        if(evt.preventDefault){evt.preventDefault();}
    }
}

...OR this script, without indexOf, using 2 for's...

validate = function(evt)
{
    var CharValidate = new Array("08", "046", "039", "948", "235");
    var number_pressed = false;
    for (i = 0; i < 5; i++)
    {
        for (Ncount = 0; Ncount < parseInt(CharValidate[i].substring(0, 1)) + 1; Ncount++)
        {
            if ((evt.keyCode || evt.which) == parseInt(CharValidate[i].substring(1, CharValidate[i].lenght)) + Ncount)
            {
                number_pressed = true;
            }
        }
    }
    if (number_pressed == false)
    {
        evt.returnValue = false;
        if(evt.preventDefault){evt.preventDefault();}
    }
}

I used the onkeydown attribute instead of onkeypress because the onkeydown attribute is checked before onkeypress attribute. The problem would be in the google chrome browser.

With the attribute "onkeypress", TAB would be uncontrollable with "preventDefault" on google chrome, however, with the attribute "onkeydown", TAB becomes controllable!

ASCII Code for TAB => 9

The first script have less code than the second, however, the array of ASCII characters must have all the keys.

The second script is much bigger than the first, but the array does not need all keys, the first digit in each position of the array is the number of times each position will be readed. For each reading, will be incremented 1 to the next one. For example:




NCount = 0

48 + NCount = 48

NCount + +

48 + NCount = 49

NCount + +

...

48 + NCount = 57




In the case of numerical keys are only 10 (0 - 9), but if they were 1 million would not make sense to create an array with all these keys.

ASCII Codes:

  • 8 ==> (Backspace);
  • 46 => (Delete);
  • 37 => (left arrow);
  • 39 => (right arrow);
  • 48 - 57 => (numbers);
  • 36 => (home);
  • 35 => (end);

I'm gonna sleep now!!

This is my first post on StackOverflow :P

share|improve this answer

Give the input field a class (<input class="digit" ...> ) and use jquery as below .

jQuery(document).ready(function () {
            jQuery('input.digit').live('input keyup',function(e){ jQuery(this).val(jQuery(this).val().replace( /[^\d]/g ,'')); });
});

Above code also works to disable special characters in Ctrl+V strokes and right click strokes also.

share|improve this answer

Remember the regional differences (Euros use periods and commas in the reverse way as Americans), plus the minus sign (or the convention of wrapping a number in parentheses to indicate negative), plus exponential notation (I'm reaching on that one).

share|improve this answer
    
Continental Europeans do, anyway. In the UK, and here in Ireland, we use commas and decimal points the same way you do for numbers. Indeed, I think this use of commas and decimal points is common to the entire English-speaking world. – TRiG Jul 1 '10 at 14:58

protected by Community Jun 17 '14 at 15:44

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.