Allow only numbers to be typed in a textbox

Javascript

Javascript Problem Overview


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

<input type="text" class="textfield" value="" id="extra7" name="extra7">

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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]*$" />

Solution 3 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEnexoOnomaView Question on Stackoverflow
Solution 1 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 2 - JavascriptpowtacView Answer on Stackoverflow
Solution 3 - JavascriptArnout EngelenView Answer on Stackoverflow