97

How to allow only numbers to be written in this textbox ?

<input type="text" class="textfield" value="" id="extra7" name="extra7">
Zoe
  • 27,060
  • 21
  • 118
  • 148
EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179
  • 4
    What do you class as a number? Are these numbers `12.3`, `-4`, `V`, `six`? – Ash Burlaczenko Sep 03 '11 at 21:07
  • 8
    Not sure if a jquery question would be a duplicate. Javascript != jQuery – Evert Sep 03 '11 at 21:31
  • 9
    **This isn't an exact duplicate** of the referenced question. This targets a javascript answer while the other targets a jQuery answer. Different audiences, different solutions. – Rob Hruska Sep 04 '11 at 02:20
  • Shortest Answer is onkeypress='return event.charCode>31 && (event.charCode <= 48 || event.charCode >= 57)' – CyberAbhay May 16 '17 at 07:51
  • const onlyNumbers = (event) => { event.preventDefault(); const asciiCode = event.target.value.charCodeAt(0); (asciiCode < 48 || asciiCode > 57) ? event.target.value = '' : event.target.value = event.target.value; } – Said Pc Aug 05 '21 at 15:01

3 Answers3

278

You could subscribe for the onkeypress event:

<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />

and then define the isNumber function:

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

You can see it in action here.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 3
    I'm not sure how to interpret your `if` clause. If it's larger than 57, it's always larger than 31. I think you can eliminate the parentheses. – pimvdb Sep 03 '11 at 21:04
  • Thank it is working. What is the chars code range for only letters? I mean I want to do it to accept letters only also in a different function of course – EnexoOnoma Sep 03 '11 at 21:06
  • @Giorkouros, here's the ASCII table: http://www.asciitable.com/ Depending on what you mean by letters the result will be different. For example if you want A-Z, then the range is [65, 90], and a-z is [97, 122]. – Darin Dimitrov Sep 03 '11 at 21:07
  • Its excellent and working-well. – Serkan Aug 16 '13 at 07:57
  • 19
    That doesn't work if you c/p some text – Aleksandar Toplek Aug 23 '13 at 09:35
  • 4
    I can still copy and paste non numeric values in the textbox – Baaju Dec 25 '13 at 03:54
  • Unfortunately there's no definitive way (short of using Flash) to prevent pasting of non numeric values. That's why it's always important to validate form input on submit. – daniel0mullins Feb 05 '14 at 20:17
  • Works. Can someone pls tell me how to get the final value in the textbox once this validated? – Grish Aug 28 '14 at 07:36
  • It works. Copy and paste is allowed only if we paste via mouse (on right button of mouse). If we use Ctrl+C and Ctrl+V to input then this code works great and not allow paste texts. +1 and thanks – Severe Torture May 05 '15 at 06:39
  • This is the definitive way to solve this issue once and for all: https://gist.github.com/nbouvrette/84ef4f498ac06cdd5b60 – Nicolas Bouvrette Jan 02 '16 at 15:25
  • Thanks :) its work for me 1+ – Codeone Feb 16 '16 at 10:39
  • I tried this, it works perfectly on Chrome and IE but not on Firefox. In firefox, pressing the delete key will not delete. It will not do anything. Anyone faces this issue? – user1149244 Sep 07 '16 at 09:19
  • Accepted solution here http://stackoverflow.com/questions/31168918/html-keycodes-not-working-in-firefox , works in all browsers – user1149244 Sep 07 '16 at 09:45
  • 1
    Doesn't work on mobile (Android + Chrome) – Gianluca Demarinis Feb 04 '17 at 11:41
  • 2
    Just accepting numeric values from the alphabetic part of keyboard. Why this function is not accepting numeric keypad keys situated on the right side of keyboard? – Rashid Sep 25 '17 at 07:54
  • Not working property as no. can be negative also – Gaurav Aggarwal Oct 11 '17 at 11:55
  • as November 2017, this is throwing an error in chrome "Uncaught ReferenceError: evt is not defined". The first line should be: var evt = (evt) ? evt : window.event; – Chux Nov 15 '17 at 09:37
  • 1
    To include the numpad characters: `if ((charCode >= 48 && charCode <= 57) || ((charCode >= 96 && charCode <= 105))) { return true; } return false;` – Milana Jun 13 '18 at 11:59
  • @Milana this makes impossible to select all text, use tab or left right, backspace and copy/paste text. – RN Kushwaha Jul 03 '18 at 06:52
  • Not working properly! It accepts special characters like !"#$%&/ etc. – karlo1zg Sep 25 '19 at 10:13
  • this is not working when i open page in mobile browser – Varun Chawla Dec 02 '19 at 13:11
  • @DarinDimitrov This code works absolutely fine, but I have a text-box field which represents "Discount" for the product and that discount can be in decimal. How could we allow Dot(.) to be be able to put into textbox? Appreciate your help – sForSujit Dec 05 '19 at 11:55
  • Check here https://stackoverflow.com/a/31169709/4093658 – Kishan Chauhan Apr 08 '21 at 10:25
50

With HTML5 you can do

<input type="number">

You can also use a regex pattern to limit the input text.

<input type="text" pattern="^[0-9]*$" />
Håken Lid
  • 22,318
  • 9
  • 52
  • 67
powtac
  • 40,542
  • 28
  • 115
  • 170
  • 32
    This does not prevent non-numeric characters from being entered. – MyNameIsKo Jun 12 '15 at 14:14
  • 1
    @MyNameIsKo it should, maybe you are using a client that does not support this kind of HTML5 feature? – powtac Jun 12 '15 at 14:18
  • 1
    it does not work in either Chrome or Firefox. You may be referring to submission validation of non-numeric characters, which does work properly with HTML5. The original question, however, was interested in preventing the non-numeric entry entirely. I'm pretty sure JavaScript is still the only way to do this. – MyNameIsKo Jun 12 '15 at 14:28
  • I see, but what does "entry" mean? One can not prevent what a user types on his keyboard while this element is active... – powtac Jun 12 '15 at 18:17
  • By entry, I mean character input into a textbox. Using JavaScript, you absolutely can prevent a user from entering certain characters, just look at the accepted answer. Obviously, user's can still break this, but it's better than nothing. – MyNameIsKo Jun 15 '15 at 14:34
  • @powtac yes you can... have you ever used Angular or any other JS frameworks? – trickpatty Jun 17 '15 at 19:53
  • 5
    Allows "." , which may not be desirable – ALLSYED Aug 12 '16 at 10:27
  • input type number and pattern both allowing alphabets to enter in field in my browser i.e chrome – Rashid Oct 09 '18 at 06:02
  • 2
    The type number is not supporting on Firefox. – PKPrabu Sep 18 '19 at 10:14
16

You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0").

Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.

Arnout Engelen
  • 6,709
  • 1
  • 25
  • 36