How can I only allow numbers (even when copied) in an input textbox using jQuery?

I am using this jQuery code to allow only numbers to be entered into an input textbox.

jQuery(document).ready(function() {     
    jQuery( '.only_numbers' ).keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if (jQuery.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A, Command+A
            ((e.keyCode === 65) && (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();
        }
    });
});

      

This works great except for one small problem. It does not allow you to insert anything into the field. How can I allow the user to insert a string into a field only if the string contains all numeric characters?

Also, it would be cool if I could do the same for text input fields that only accept alphabets.

+3


source to share


8 answers


Your HTML

 <input type='text' />

      

Your Jquery



 $('input').on('paste', function (event) {
  if (event.originalEvent.clipboardData.getData('Text').match(/[^\d]/)) {
    event.preventDefault();
  }
});

$("input").on("keypress",function(event){
                if(event.which <= 48 || event.which >=57){
                    return false;
                }
            });

      

Working Code https://codepen.io/anon/pen/pwEXyg

+6


source


You can use regular expressions to accomplish this.

Only numbers.

function process(input){
  let value = input.value;
  let numbers = value.replace(/[^0-9]/g, "");
  input.value = numbers;
}
      

<input type="text" oninput="process(this)">
      

Run codeHide result




Only letters.

function process(input){
  let value = input.value;
  let letters = value.replace(/[0-9]/g, "");
  input.value = letters;
}
      

<input type="text" oninput="process(this)">
      

Run codeHide result


+5


source


Why are you doing it so hard. You can just do some input type='number'

and that will serve your purpose, for which you don't need jQuery. It doesn't allow alphabets other than e

for exponential numbers, and when you copy the patch into it, it just pastes the numbers from the copied string into the textbox and e

.

Also below is the code that will only allow alphabets in the textbox. And also a code that only allows numbers in the text box type=text

.

function onlyAlphabets(event) {
  //allows only alphabets in a textbox
  if (event.type == "paste") {
    var clipboardData = event.clipboardData || window.clipboardData;
    var pastedData = clipboardData.getData('Text');
    if (isNaN(pastedData)) {
      return;

    } else {
      event.prevetDefault();
    }
  }
  var charCode = event.which;
  if (!(charCode >= 65 && charCode <= 120) && (charCode != 32 && charCode != 0) && charCode != 8 && (event.keyCode >= 96 && event.keyCode <= 105)) {
    event.preventDefault();
  }
}

function onlyNumbers(event) {
  if (event.type == "paste") {
    var clipboardData = event.clipboardData || window.clipboardData;
    var pastedData = clipboardData.getData('Text');
    if (isNaN(pastedData)) {
      event.preventDefault();

    } else {
      return;
    }
  }
  var keyCode = event.keyCode || event.which;
  if (keyCode >= 96 && keyCode <= 105) {
    // Numpad keys
    keyCode -= 48;
  }
  var charValue = String.fromCharCode(keyCode);
  if (isNaN(parseInt(charValue)) && event.keyCode != 8) {
    event.preventDefault();
  }
}
      

Number Only With Type=Number:
<input type="number" name="quantity" min="1" max="5">
<br> Number Only With Type=Text:
<input type="text" name="quantity" min="1" max="5" onkeydown="onlyNumbers(event)" onpaste="onlyNumbers(event)">
<br>Aplhabets Only:
<input type="text" onkeydown="onlyAlphabets(event)" onpaste="onlyAlphabets(event)"/>
      

Run codeHide result


Update

Added a code allowing only numbers to be entered in the input type=text

. And will also work in Firefox and IE

Hope this helps :)

+2


source


If you want to do this, skipping the JS, you can just give your input type = "number". Although it doesn't work for the alphabet ...

+2


source


Try this, it will limit the letter set and prevent you from inserting it.

$(document).ready(function(){
    $("#test").on("keypress",function(event){
        if(event.which <= 48 || event.which >=57){
            event.preventDefault();
        }
    });
    
    $("#test").on("change",function(event){
        $value = $("#test").val();
        if(isNaN($value)){
          $("#test").val('');
        }
    });
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test">
      

Run codeHide result


+2


source


Here is my solution which is faster than JS.

<input type="text" pattern="[\d+\t.]+" formnovalidate="false"/>

      

0


source


In fact, you only need the "pattern" attribute.

<input type="text" pattern="[\d\t.]+" formnovalidate="false "/>

      

0


source


Restrict other keys using keyboard event

//numbers, delete, backspace, arrows        
var validKeyCodes = [8, 9, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
        $("Selectors").on("keydown", function (e) {
            if (!($.inarray(e.keycode, validkeycodes) >= 0))
                e.preventDefault();
        });

      

0


source







All Articles