Javascript: how to check if a key is pressed in a digit form field (0 - 9)?

I am using the onkeyup event in a form field in JavaScript, and I want to check if a key is a pressed key - that is. 0 - 9, so I can do something with input.

<input type="text" onkeyup="" />

Should I use Regex for this?

thanks

+5
source share
5 answers

I used the following function to check if a given string is a number or not

// Validate Numeric inputs
function isNumber(o) {
    return o == '' || !isNaN(o - 0);
}

Assuming your key code in the keyup or keydown event is in the keyCode variable:

var keyCode = e.keyCode || e.which;
if (keyCode >= 96 && keyCode <= 105) {
        // Numpad keys
        keyCode -= 48;
}
console.log(isNumber(String.fromCharCode(keyCode)));
+1
source

event.key, . , , isFinite

input.addEventListener("keydown", function(event) {
    const isNumber = isFinite(event.key);
});

HTML number. ().

<input type="number">

In any case, you should clear all user data with

string.replace(/[^0-9]/g,'');
0
source

only 0-9 is allowed, other letters are swallowed.

$('#id').keypress(function (e) {
            var validkeys = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];
            if (validkeys.indexOf(e.key) < 0)
                return false;
        });
0
source

See this:

http://www.javascriptkit.com/javatutors/javascriptkey2.shtml

<script type="text/javascript">
function displayunicode(e){
var unicode=e.keyCode? e.keyCode : e.charCode
if unicode >= 48 && unicode <= 57 {
    alert('number')
}
else{
}
    alert('nonnumber')
}
</script>
<form>
<input type="text" size="2" maxlength="1" onkeyup="displayunicode(event); this.select()" />
</form>
-1
source

All Articles