我有输入框 jsfiddle 链接,其中包含我所做的示例代码 https://jsfiddle.net/4rsv960t/173/ 我想允许仅包含数字的粘贴事件(如果它不是数字),然后自动清空文本框。
仅允许编号我的示例代码
$(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) {
console.log('allownumericwithoutdecimal called');
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
<input type="text" value="" class="allownumericwithoutdecimal"/>
最佳答案
就这么简单
$(".allownumericwithoutdecimal").on("input", function(event) {
this.value = /^\d+$/.test(this.value) ? this.value : "";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" class="allownumericwithoutdecimal" />
或者保留数字
$(".allownumericwithoutdecimal").on("input", function(event) {
this.value = this.value.replace(/\D/g, "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" class="allownumericwithoutdecimal" />
关于jquery - 鼠标右键粘贴在所有浏览器中只允许数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51264926/