如何在jquery+javascript中只在输入框中输入数字(使用regex)

how to enter only number in input box(using regex) in jquery + javascript?

本文关键字:输入 使用 regex 数字 jquery+javascript      更新时间:2023-09-26

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