簡體   English   中英

如何在jQuery + 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" />&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上不必要的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM