我正在尝试让我的输入只接受Numbers和'。',它工作得很好,但它不允许数字键盘数字键。我似乎无法在网上找到确切的答案。
HTML
<input type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#" onkeypress="return isNumeric(event)" onkeydown="return keyispressed(event);">
的JavaScript
//prevent , and $ from being input
function keyispressed(e){
var charval= String.fromCharCode(e.keyCode);
if(isNaN(charval) && (e.which != 8 ) && (e.which != 190 )){
return false;
}
return true;
}
//is input numeric
function isNumeric (evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode (key);
var regex = /[0-9]|\./;
if ( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
感谢您的帮助!
答案 0 :(得分:1)
我认为最好的方法是在只允许数字的所有输入中添加一个类。然后,您可以限制任何与模式或数字/小数不匹配的输入。
function numberVerfication(value) {
var pattern=/^[0-9]*(\.)?[0-9]*$/;
if (value.match(pattern) != null){
return value
}
else {
var p=/[0-9]*(\.)?[0-9]*/;
return value.match(p)[0];
}
}
$('.numbersOnly').keyup(function(e) {
e.target.value = numberVerfication(e.target.value);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class='numbersOnly' type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#">
&#13;
答案 1 :(得分:0)
使用REGEXP
<强> HTML 强>
<input type="text" class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct">
<强> JQUERY 强>
$('.numbersOnly').keyup(function (e) {
this.value = this.value.replace(/[^0-9\.]/g, '');
});
JAVA SCRIPT
function numValidate(that){
that.value = that.value.replace(/[^0-9\.]/g, '');
}
<input type="text" onkeypress='numValidate(this)' onkeyup='numValidate(this)' class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct"/>
<强> Demo 强>
答案 2 :(得分:0)
function numberVerfication(value){
return value.replace(/[^0-9.\-+]/g, '');
}
$('.numbersOnly').keyup(function(e){
e.target.value=numberVerfication(e.target.value);
});
&#13;