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

标签 javascript jquery 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;
    }*/
   });
});

谢谢

最佳答案

这会起作用:

$(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/

相关文章:

javascript - 在 jQuery 或 Javascript 中切换按钮选择的大小写

jQuery "thumbnail"函数

python - 使用正则表达式匹配任意数量的字符,只要第一个字符不是数字

Java从字符串中提取部分的最佳方法

javascript - Chrome 控制台从变量返回 8 Nan

javascript - 如何更改jquery mobile中的默认加载ajax加载器gif

javascript - 是否有其他编译器(例如 typescript)可以编译为 javascript

java - 如何从 servlet 发送数组并在 HTML jquery 中接收?

php - 将 PHP 的 preg_match_all 翻译成 Python

Javascript 显示表单的隐藏变量