当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Do not allow decimal and alphabet values in textbox

问题描述:

I want to restict decimal and alphabatic values in textbox. I just want to enter only numbers in textbox. And do not copy and paste th text and decimal value also. Want t enter only numbers(0 o 9). How can I do this using regex of javascript o jquery.

fiddle

See this fiddle, here everything is working. But arrow keys are not working. I can't able to move left and right, and if I give (shift+home) or (shift + end) its not selecting the value. Please help me for

$(".allownumericwithoutdecimal").on("keypress keyup blur",function (event) {

$(this).val($(this).val().replace(/[^\d].+/, ""));

if ((event.which < 48 || event.which > 57)) {

event.preventDefault();

}

});

<span>Int</span>

<input type="text" name="numeric" class='allownumericwithoutdecimal'>

<div>Numeric values only allowed (Without Decimal Point) </div>

网友答案:

$(".allownumericwithoutdecimal").on("keypress keyup blur paste", function(event) {
    var that = this;

    //paste event 
    if (event.type === "paste") {
        setTimeout(function() {
            $(that).val($(that).val().replace(/[^\d].+/, ""));
        }, 100);
    } else {

        if (event.which < 48 || event.which > 57) {
            event.preventDefault();
        } else {
            $(this).val($(this).val().replace(/[^\d].+/, ""));
        }
    }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span>Int</span>
<input type="text" name="numeric" class='allownumericwithoutdecimal'>
<div>Numeric values only allowed  (Without Decimal Point) </div>
网友答案:

Try this:

$(document).ready(function () {
  /* Allow digits only */
  $("#wdm_num").keypress(function (e) {
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
        $("#wdm_errmsg").html("Please Enter Digits Only").show().fadeOut("slow");
               return false;
    }
   });
   /* Do not allow paste */
   $('#wdm_num').bind("paste",function(e) {
          e.preventDefault();
      });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" name="wdm_num" id="wdm_num" />&nbsp;<span id="wdm_errmsg"></span>
分享给朋友:
您可能感兴趣的文章:
随机阅读: