Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow only numbers (even when copy-pasted) in input text field using jQuery?

Tags:

jquery

I am using this jQuery code to allow only numbers to be entered in input text field.

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 fine, except one small problem. It does not allow anything to be pasted in the field. How can I allow user to paste a string in the field, only if the string contains all numeric characters?

Also, it will be awesome if I could do the same for input text fields allowing only alphabets.

like image 965
user1543784 Avatar asked Jun 15 '17 04:06

user1543784


People also ask

How do I allow only numbers in input text field?

By default, HTML 5 input field has attribute type=”number” that is used to get input in numeric format. Now forcing input field type=”text” to accept numeric values only by using Javascript or jQuery. You can also set type=”tel” attribute in the input field that will popup numeric keyboard on mobile devices.

How do I restrict copy and paste in jQuery?

Projects In JavaScript & JQuery To disable cut, copy and paste of a content in jQuery, use the jQuery bind() function.

How can we avoid copy paste in textbox using jQuery?

By using an on() method: It is a built-in method in jQuery. With the help of this method, we will able to disabled the cut, copy, paste and right-click option. // Disables ctrl+v, ctrl+x, ctrl+c.


5 Answers

You can use regex to achieve this.

Numbers only.

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

Letters only.

function process(input){
  let value = input.value;
  let letters = value.replace(/[0-9]/g, "");
  input.value = letters;
}
<input type="text" oninput="process(this)">
like image 110
Zze Avatar answered Nov 10 '22 00:11

Zze


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 >58){
                    return false;
                }
            });

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

like image 20
Saroj Avatar answered Nov 10 '22 01:11

Saroj


Why are you making things so complicated. You can just make the input type='number' and that would serve your purpose you don't need jQuery for that. It wont allows alphabets except e for exponential numbers and when you copy paste to this it will just paste the numbers from the copied string to the textbox and e as well.

Also below is the code that will allow only alphabets in a textbox. And also the code that allows only numbers in a textbox of 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)"/>

Update

Added code to allow only numbers in an input of type=text. And also will work in Firefox and IE as well

Hope it helps :)

like image 45
Manish Avatar answered Nov 10 '22 01:11

Manish


If, you wanted to do it by skipping the JS you could just set your input type="number". Though it does not work for alphabet...

like image 37
Icewine Avatar answered Nov 10 '22 01:11

Icewine


Try this, it will restrict typing alphabets and won't let you paste it either.

$(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">
like image 26
Rudraksh Pathak Avatar answered Nov 09 '22 23:11

Rudraksh Pathak