简体   繁体   中英

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

could you please tell me how to make a input field in which user only enter numbers using regex.i am able to do using ascii values .But I need to do this using regular expression

here is my code 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

This would work:

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

Or here's a working jsFiddle

$('input').keyup(function(e){

    if(!/^[0-9]*$/.test(this.value)){

        this.value = this.value.split(/[^0-9.]/).join('');

    }

});

I would instead preventDefault the unwanted keyCode on keydown . That way you don't have to do any string manipulation and then replace the input value, which could look awkward, kind I'd like a flash.

$( '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.
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM