Search code examples
javascriptjqueryregexkeycode

Allow only numbers and ctrl+a , ctrl+v , ctrl+c to a textbox



I am trying to allow users enter only numbers and copy and paste control to the textbox. I am able to restrict user to enter only numbers but copy,paste is not working for me help me to fix this.

Here is my script:

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

Here is the jsfiddle link:

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


Solution

  • Try with event.keyCode and event.metaKey like this.

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

    EDIT:

    Remove the following code snippets from your code.

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

    Because ctrlDown will be false while pressing C and V for copy and paste. And hence your ctr+c and ctrl+v is not working.