Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery function to allow only alphabets in textbox not working

I use the following JQuery function to restrict users from writing numeric values in the textbox. The code works fine but the problem is that it also restrict users from using other characters like full stop(.), comma(,), $, @ and other signs..It also does not allow users to use the options of copy and past. I only want to restrict the users from writing numeric values or numbers but the user should be allowed to use other characters.

$(function() {
  $('.txtOnly').keydown(function(e) {
    if (e.shiftKey || e.ctrlKey || e.altKey) {
      e.preventDefault();
    } else {
      var key = e.keyCode;
      if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) {
        e.preventDefault();
      }
    }
  });
});
like image 992
Ajmal Razeel Avatar asked Jul 28 '16 09:07

Ajmal Razeel


People also ask

How do I allow only the letters in the input field?

To get a string contains only letters (both uppercase or lowercase) we use a regular expression (/^[A-Za-z]+$/) which allows only letters. Next the match() method of string object is used to match the said regular expression against the input value. Here is the complete web document.

How do I restrict a TextBox?

_%+-]+@[a-z0-9. -]+\. [a-z]{2,3}$"> will restrict the allowed characters according that RegExp pattern (in this case: valid-looking email addresses). The title attribute will be used as a warning / notification when the user tries to submit the data not matching the requirement.

What is $() in jQuery?

$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.


1 Answers

Hope this helps:

<!DOCTYPE html>

<html lang="en">
    <head>
        <script src="jquery-1.12.2.js"></script>
    </head>
    <body>
        <input class="txtOnly" id="txtOnly" name="txtOnly" type="text" />
        <script>
            $( document ).ready(function() {
                $( ".txtOnly" ).keypress(function(e) {
                    var key = e.keyCode;
                    if (key >= 48 && key <= 57) {
                        e.preventDefault();
                    }
                });
            });
        </script>
    </body>
</html>
like image 116
Tim Kruger Avatar answered Oct 27 '22 07:10

Tim Kruger