如何在jquery+javascript中只在输入框中输入数字(使用regex)
how to enter only number in input box(using regex) in jquery + javascript?
你能告诉我如何创建一个用户只使用正则表达式输入数字的输入字段吗?我可以使用ascii值。但我需要使用正则表达式
这是我的代码http://jsfiddle.net/HkEuf/6100/
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
var BlkAccountIdV = $('#quantity').val();
var re = /[^0-9]/g;
if ( re.test(BlkAccountIdV) ){
console.log("=====")
errorflag=1;
}else {
console.log("==tt===")
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
/*if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}*/
});
});
Thnaks
这将起作用:
$(document).ready(function () {
//called when key is pressed in textbox
$("#quantity").keyup(function (e) {
// if letters found flag error, display error, and remove any non-numbers
if ($(this).val().match(/[^0-9]/g, '')) {
$("#errmsg").html("Digits Only").show().fadeOut("slow");
$(this).val($(this).val().replace(/[^0-9]/g, ''));
console.log("=====")
errorflag = 1;
} else {
console.log("==tt===")
}
});
// but users can still paste values with letters into the box with right click
// so we bind to paste event and if detected, trigger the element's keyup event
$("#quantity").bind('paste', function (e) {
setTimeout(function() { $(this).keyup(); }, 30);
});
});
#errmsg {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Number :
<input type="text" name="quantity" id="quantity" /> <span id="errmsg"></span>
或者这里有一个正在工作的jsFiddle
$('input').keyup(function(e){
if(!/^[0-9]*$/.test(this.value)){
this.value = this.value.split(/[^0-9.]/).join('');
}
});
我会将preventDefault
替换为keydown
上不需要的keyCode。这样你就不必做任何字符串操作,然后替换输入值,这可能看起来很尴尬,就像我想要一个闪光灯一样。
$( 'input' ).on( 'click', function ( e ) {
var numberKeys = [ /* the wanted keyCodes */];
if ( numberKeys.indexOf( e.keyCode ) < 0 ) {
e.preventDefault();
// do what ever you'd like here when the user types in a non numeric character.
}
});
相关文章:
- 使用javascript检查多个输入值,并在1次检查中标记多个输入框
- 离子/角度日期输入使用时刻以编程方式设置
- 反应构建选择输入使用 for 循环
- 如何根据选择输入使用 javascript 更改页面的内容
- 对表单输入使用可重用指令
- AngularJS文本输入使用ng模型,但需要默认值,而不使用value=或ng-init=
- 基于一个值对一组输入使用ng-disabled
- 如何对多个输入使用相同的$(document).ready(function() ?
- 我如何删除最后添加的<输入>使用javascript
- 根据用户输入使用Javascript显示图像
- 自动减去数字没有按钮点击基于输入使用javascript或PHP
- 我如何找到HTML5范围输入使用jquery的方向
- 根据用户输入使用jquery创建html元素
- 如何只允许数字0-5在<输入>使用AngularJS
- 在JavaScript中基于用户输入使用条件语句的问题
- 如何根据用户输入使用PHP和AJAX从XML中提取数据
- 刷新输入:使用Jquery Mobile从iframe接收无线电
- 添加“;清除字段”;按钮引导3输入使用jQuery+CSS类
- 根据输入使用Jade生成HTML
- 对编程创建的输入使用selectionStart