【问题标题】:Do not allow decimal and alphabet values in textbox不允许文本框中的小数和字母值
【发布时间】:2016-03-04 12:07:26
【问题描述】:

我想限制文本框中的十进制和字母值。我只想在文本框中输入数字。并且不要复制和粘贴文本和十进制值。不想只输入数字(0 o 9)。如何使用 javascript o jquery 的正则表达式来做到这一点。

fiddle

看到这个小提琴,这里一切正常。但是方向键不起作用。我不能左右移动,如果我给出 (shift+home) 或 (shift + end) 它没有选择值。请帮帮我

 

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

这样做。

【问题讨论】:

标签: javascript jquery html regex


【解决方案1】:

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

【讨论】:

  • 如果复制并粘贴文本或十进制值,它正在占用。我不想复制粘贴文本和十进制值。如果复制粘贴也我只想做数字
  • 请检查小提琴一次。如果我粘贴“555.55”,它只会删除小数点并将值显示为“55555”。
  • 这里我只想允许一个否定符号。它也应该允许负值...请帮助我。
  • 使用这个正则表达式 [^(-?\d{1,})].+
  • jsfiddle.net/44pc78pj/183 看看这个小提琴......如果我使用这个正则表达式,它也不会工作。请检查我是否正确添加了正则表达式?
【解决方案2】:

试试这个:

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

【讨论】:

  • 我也想做复制和粘贴。但只有数字。不是小数,也不是字符。
猜你喜欢
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-16
  • 1970-01-01
  • 2011-01-01
相关资源
最近更新 更多