有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
jQuery的另一个简单方法:
$('.Numeric').bind('keydown',function(e){
if (e.which < 48 || e.which > 57)
return false;
return true;
})
现在只需将每个输入类设置为Numeric,如下所示:
<input type="text" id="inp2" name="inp2" class='Numeric' />
其他回答
我看到了一些很好的答案,但我喜欢它们尽可能小,尽可能简单,所以也许有人会从中受益。我将使用javascript的Number()和isNaN功能,像这样:
if(isNaN(Number(str))) {
// ... Exception it is NOT a number
} else {
// ... Do something you have a number
}
希望这能有所帮助。
下面是我喜欢使用的一个很好的简单的解决方案:
function numeric_only (event, input) {
if ((event.which < 32) || (event.which > 126)) return true;
return jQuery.isNumeric ($(input).val () + String.fromCharCode (event.which));
}// numeric_only;
<input type="text" onkeypress="return numeric_only (event, this);" />
解释:
使用“事件。-首先确定它是否是一个可打印字符。如果不是,那么允许它(如删除和退格)。否则,将字符连接到字符串的末尾,并使用jQuery的“isNumeric”函数测试它。这样就避免了测试每个角色的单调乏味,也适用于剪切/粘贴场景。
如果你想变得更可爱,那么你可以创建一个新的HTML输入类型。让我们称它为“numeric”,这样你就可以有这样的标签:
<input type="numeric" />
它只允许数字字符。只需添加下面的“文档”。准备好”命令:
$(document).ready (function () {
$("input[type=numeric]").keypress (function (event) {
if ((event.which < 32) || (event.which > 126)) return true;
return jQuery.isNumeric ($(this).val () + String.fromCharCode (event.which));
});// numeric.keypress;
});// document.ready;
HTML并不关心你使用的类型名称-如果它不识别它,那么它将默认使用一个文本框,所以你可以这样做。你的编辑可能会抱怨,但这就是问题所在。毫无疑问,清教徒会抓狂,但它很有效,很简单,到目前为止对我来说还很强大。
更新
这里有一个更好的方法:它考虑到文本选择,并使用本地javascript:
verify (event) {
let value = event.target.value;
let new_value = `${value.substring (0, event.target.selectionStart)}${event.key}${value.substring (event.target.selectionEnd)}`;
if ((event.code < 32) || (event.code > 126)) return true;
if (isNaN (parseInt (new_value))) return false;
return true;
}// verify;
HTML5支持正则表达式,所以你可以使用这个:
<input id="numbersOnly" pattern="[0-9.]+" type="text">
警告:某些浏览器还不支持此功能。
再举一个例子,你可以在输入字段中只添加数字,不能添加字母
<input type="text" class="form-control" id="phone" name="phone" placeholder="PHONE" spellcheck="false" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');">
在任何击键上执行此函数,它将不允许除加号、连字符和圆括号之外的任何内容。
假设:+234-(123)1231231将工作 但不是信件
替换(/ ^[0 - 9 +()——]*美元/ test (char))与(/ ^[0 - 9]*美元/ test (char))只允许数字按键。
isNumber(e) {
let char = String.fromCharCode(e.keyCode);
if (/^[0-9+()-]*$/.test(char)) return true;
else e.preventDefault();
},