Allow only numbers to be typed in a textbox [duplicate]
Asked Answered
E

3

99

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

<input type="text" class="textfield" value="" id="extra7" name="extra7">
Erector answered 3/9, 2011 at 20:58 Comment(5)
What do you class as a number? Are these numbers 12.3, -4, V, six?Manuelmanuela
Not sure if a jquery question would be a duplicate. Javascript != jQueryCia
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.Adriannaadrianne
Shortest Answer is onkeypress='return event.charCode>31 && (event.charCode <= 48 || event.charCode >= 57)'Recipe
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; }Telpherage
A
281

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.

Aussie answered 3/9, 2011 at 21:2 Comment(22)
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.Unpolled
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 courseErector
@Giorkouros, here's the ASCII table: 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].Aussie
That doesn't work if you c/p some textCarabao
I can still copy and paste non numeric values in the textboxKirakiran
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.Bourges
Works. Can someone pls tell me how to get the final value in the textbox once this validated?Pukka
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 thanksAkins
This is the definitive way to solve this issue once and for all: gist.github.com/nbouvrette/84ef4f498ac06cdd5b60Baty
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?Radically
Accepted solution here #31169418 , works in all browsersRadically
Doesn't work on mobile (Android + Chrome)Auricular
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?Recrement
Not working property as no. can be negative alsoEr
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;Nellanellda
To include the numpad characters: if ((charCode >= 48 && charCode <= 57) || ((charCode >= 96 && charCode <= 105))) { return true; } return false;Cogwheel
@Cogwheel this makes impossible to select all text, use tab or left right, backspace and copy/paste text.Desiraedesire
Not working properly! It accepts special characters like !"#$%&/ etc.Sarsaparilla
this is not working when i open page in mobile browserHazlip
@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 helpLactometer
Check here https://mcmap.net/q/48379/-html-keycodes-not-working-in-firefoxNibelung
What happens if input occurs from a non-keypress? For example, an external source manipulating an input field.Bloodline
F
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]*$" />
Fellow answered 3/9, 2011 at 21:1 Comment(9)
This does not prevent non-numeric characters from being entered.Uchish
@Uchish it should, maybe you are using a client that does not support this kind of HTML5 feature?Fellow
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.Uchish
I see, but what does "entry" mean? One can not prevent what a user types on his keyboard while this element is active...Fellow
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.Uchish
@Fellow yes you can... have you ever used Angular or any other JS frameworks?Binominal
Allows "." , which may not be desirableBrigadier
input type number and pattern both allowing alphabets to enter in field in my browser i.e chromeRecrement
The type number is not supporting on Firefox.Ineluctable
C
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.

Coastward answered 3/9, 2011 at 21:4 Comment(1)
The type number and min are not supporting on FirefoxIneluctable

© 2022 - 2024 — McMap. All rights reserved.