Is there a quick way to set an HTML text input () to only allow numeric keystrokes (plus \'.\')?
A safer approach is checking the value of the input, instead of hijacking keypresses and trying to filter keyCodes.
This way the user is free to use keyboard arrows, modifier keys, backspace, delete, use non standard keyboars, use mouse to paste, use drag and drop text, even use accessibility inputs.
The below script allows positive and negative numbers
1
10
100.0
100.01
-1
-1.0
-10.00
1.0.0 //not allowed
var input = document.getElementById('number');
input.onkeyup = input.onchange = enforceFloat;
//enforce that only a float can be inputed
function enforceFloat() {
var valid = /^\-?\d+\.\d*$|^\-?[\d]*$/;
var number = /\-\d+\.\d*|\-[\d]*|[\d]+\.[\d]*|[\d]+/;
if (!valid.test(this.value)) {
var n = this.value.match(number);
this.value = n ? n[0] : '';
}
}
<input id="number" value="-3.1415" placeholder="Type a number" autofocus>
EDIT: I removed my old answer because I think it is antiquated now.
I saw some great answers however I like them as small and as simple as possible, so maybe someone will benefit from it. I would use javascript Number()
and isNaN
functionality like this:
if(isNaN(Number(str))) {
// ... Exception it is NOT a number
} else {
// ... Do something you have a number
}
Hope this helps.
You can use pattern for this:
<input id="numbers" pattern="[0-9.]+" type="number">
Here you can see the complete mobile website interface tips.
Here is a simple one which allows for exactly one decimal, but no more:
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');" />
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);"/>
A easy way to resolve this problem is implementing a jQuery function to validate with regex the charaters typed in the textbox for example:
Your html code:
<input class="integerInput" type="text">
And the js function using jQuery
$(function() {
$('.integerInput').on('input', function() {
this.value = this.value
.replace(/[^\d]/g, '');// numbers and decimals only
});
});
$(function() {
$('.integerInput').on('input', function() {
this.value = this.value
.replace(/[^\d]/g, '');// numbers and decimals only
});
});
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous">
</script>
<input type="text" class="integerInput"/>