Is there a quick way to set an HTML text input () to only allow numeric keystrokes (plus \'.\')?
This is the extended version of geowa4's solution. Supports min
and max
attributes. If the number is out of range, the previous value will be shown.
You can test it here.
Usage:
function number(e) {
var theEvent = e || window.event;
var key = theEvent.keyCode || theEvent.which;
if(key!=13&&key!=9){//allow enter and tab
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key)) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
}
$(document).ready(function(){
$("input[type=text]").filter(".number,.NUMBER").on({
"focus":function(e){
$(e.target).data('oldValue',$(e.target).val());
},
"keypress":function(e){
e.target.oldvalue = e.target.value;
number(e);
},
"change":function(e){
var t = e.target;
var min = $(t).attr("min");
var max = $(t).attr("max");
var val = parseInt($(t).val(),10);
if( val
If the inputs are dynamic use this:
$(document).ready(function(){
$("body").on("focus","input[type=text].number,.NUMBER",function(e){
$(e.target).data('oldValue',$(e.target).val());
});
$("body").on("keypress","input[type=text].number,.NUMBER",function(e){
e.target.oldvalue = e.target.value;
number(e);
});
$("body").on("change","input[type=text].number,.NUMBER",function(e){
var t = e.target
var min = $(t).attr("min");
var max = $(t).attr("max");
var val = parseInt($(t).val());
if( val