gpt4 book ai didi

javascript - 如何在 jquery + javascript 的输入框(使用正则表达式)中只输入数字?

转载 作者:行者123 更新时间:2023-11-30 16:57:26 26 4
gpt4 key购买 nike

你能告诉我如何制作一个用户只能使用正则表达式输入数字的输入字段吗?我可以使用 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;
}*/
});
});

谢谢

最佳答案

这会起作用:

$(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" />&nbsp;<span id="errmsg"></span>

或者这里是working jsFiddle

关于javascript - 如何在 jquery + javascript 的输入框(使用正则表达式)中只输入数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29453347/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com