仅允许数字和ctrl + a,ctrl + v,ctrl + c到文本框

时间:2015-10-21 04:39:23

标签: javascript jquery regex keycode


我试图允许用户只输入数字并将控件复制并粘贴到文本框中。我可以限制用户只输入数字,但复制,粘贴不起作用,帮助我解决这个问题。

这是我的剧本:

$(".allow_only_numbers").keydown(function (e) {
    var ctrlDown = false;
    var ctrlKey = 17, vKey = 86, cKey = 67;
    if (e.keyCode === ctrlKey){
        ctrlDown = true;
    }
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
            // Allow: Ctrl
        (e.keyCode === ctrlKey) ||
            // Allow: Ctrl+A
        (e.keyCode === 65 && e.ctrlKey === true) ||
            // Allow: Ctrl+v
        (e.keyCode === vKey && ctrlDown) ||
            // Allow: Ctrl+c
        (e.keyCode === cKey && ctrlDown) ||
            // Allow: home, end, left, right, down, up
        (e.keyCode >= 35 && e.keyCode <= 40)) {
        // let it happen, don't do anything
        return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
});

这是jsfiddle链接:

https://jsfiddle.net/sureshpattu/stwzhceL/1/

8 个答案:

答案 0 :(得分:17)

尝试使用此event.keyCodeevent.metaKey

$(document).ready(function() {
  $(".allow_only_numbers").keydown(function(e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
      // Allow: Ctrl+A,Ctrl+C,Ctrl+V, Command+A
      ((e.keyCode == 65 || e.keyCode == 86 || e.keyCode == 67) && (e.ctrlKey === true || e.metaKey === true)) ||
      // Allow: home, end, left, right, down, up
      (e.keyCode >= 35 && e.keyCode <= 40)) {
      // let it happen, don't do anything
      return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
      e.preventDefault();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="number" class="allow_only_numbers" />

修改

从代码中删除以下代码段。

var ctrlDown = false;
var ctrlKey = 17, vKey = 86, cKey = 67;
if (e.keyCode === ctrlKey) {
    ctrlDown = true;
}

因为在ctrlDownfalse进行复制和粘贴时,C将为V。因此,ctr+cctrl+v无效。

答案 1 :(得分:5)

$(".allow_only_numbers").on("input",function (e) {
  e.target.value = e.target.value.replace(/[^0-9]/g,'')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="allow_only_numbers" />

答案 2 :(得分:1)

$(".allow_only_numbers").keydown(function (e) {
        var isModifierkeyPressed = (e.metaKey || e.ctrlKey || e.shiftKey);
        var isCursorMoveOrDeleteAction = ([46,8,37,38,39,40].indexOf(e.keyCode) != -1);
        var isNumKeyPressed = (e.keyCode >= 48 && e.keyCode <= 58) || (e.keyCode >=96 && e.keyCode <= 105);
        var vKey = 86, cKey = 67,aKey = 65;
        switch(true){
            case isCursorMoveOrDeleteAction:
            case isModifierkeyPressed == false && isNumKeyPressed:
            case (e.metaKey || e.ctrlKey) && ([vKey,cKey,aKey].indexOf(e.keyCode) != -1):
                break;
            default:
                e.preventDefault();
        }
});

这是工作示例

https://jsfiddle.net/stwzhceL/8/

这允许您ctrl+actrl+cctrl+v以及箭头键,删除键和退格键。

此代码还包括mac。(cmd+a/cmd+c/cmd+v

答案 3 :(得分:1)

$('.numericOnly').on('keydown keyup', function (e) {
    // Allow: backspace, delete, tab, escape, enter and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
        // Allow: Ctrl+A,Ctrl+C,Ctrl+V, Command+A
        ((e.keyCode == 65 || e.keyCode == 86 || e.keyCode == 67) && (e.ctrlKey === true || e.metaKey === true)) ||
        // Allow: home, end, left, right, down, up
        (e.keyCode >= 35 && e.keyCode <= 40)) {
        // let it happen, don't do anything
        return;
    }
    // Ensure that it is a number and stop the keypress
    if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
        e.preventDefault();
    }
    //Ensure that bulk number pasted is numeric only
    let n = $(this).val()
    if (!isNaN(parseFloat(n)) && isFinite(n)) {
    } else {
        $(this).val("")
    }
})

答案 4 :(得分:0)

如果您将keydown事件更改为keyup事件,则可以使用e.ctrlKey,按下true键时将ctrl。< / p>

答案 5 :(得分:0)

function numbersonly(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}

答案 6 :(得分:0)

这应该会给你一个想法。对不起,我在Mac上,据我所知,e.ctrlKey等在Mac上不起作用。

var mod;

var ouput = jQuery('#output');


var numeric = jQuery('#numeric').keydown(function(e){
  mod = e.which;
  
  if(!(e.which >= 48 && e.which <= 57) && (e.which != 8)
  && (mod && (e.which == 67 || e.which != 86))){
      e.preventDefault();
  }
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='numeric'/>

<label id='output'></label>

答案 7 :(得分:0)

来自@Shanimal答案。 这是我的角度js指令。只使用数字作为输入。

.directive('onlyNumber', function() {
        return  {
            restrict: 'A',
            link: function (scope, elm, attrs, ctrl) {
                elm.on("propertychange input",function (event) {
                    event.target.value = event.target.value.replace(/[^0-9]/g,'');
                });
            }
        };
    })

只需在元素中使用“仅数字”即可。 例子:

<input type="text" data-ng-model="number" placeholder="number"id="cifNumber" only-number/>