[英]How to give a permission to the user to enter only number between 1 to 100 using jQuery or javaScript
[英]how to enter only number in input box(using regex) in jquery + javascript?
能否请您告诉我如何在用户仅使用regex输入数字的情况下创建输入字段?我可以使用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>
$('input').keyup(function(e){
if(!/^[0-9]*$/.test(this.value)){
this.value = this.value.split(/[^0-9.]/).join('');
}
});
我反而preventDefault
上不必要的keyCode keydown
。 这样,您不必进行任何字符串操作,然后替换输入值,这看起来很尴尬,这就像我想要的那样。
$( '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.
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.