How to accept only alphanumeric keys pressed (for the purpose of "autocomplete")

I am wondering ... how to accept only alphabetic keystrokes from the keyboard .. I use the jQuery.keypress method ... now I want to know how to filter the passed key ...

I am trying to create a simple autocomplete plugin for jQuery ... I know about the jQuery user interface, but I want to do it myself ...

early:)

+4
source share
4 answers

You can bind a function to a field that replaces everything that is not in the az range.

<input name="lorem" class="alphaonly" /> <script type="text/javascript"> $('.alphaonly').bind('keyup blur',function(){ $(this).val( $(this).val().replace(/[^az]/g,'') ); }); </script> 

Source: Allow text box for letters only using jQuery?

+2
source

In your callback, you can check the keyCode event keyCode . If you want to block key entry, just return false . For instance:

 $('#element').keypress(function(e) { if(e.which < 65 || e.which > 90) //65=a, 90=z return false; }); 

Please note that this will not work very well. The user can still insert other text or use a mouse-based input device or any other.

I edited this based on Tim Down's comment and replaced keyCode with which , which is true for keydown , keyup and keypress .

+1
source

The following will prevent the registration of any character entered outside the register az and AZ.

 $("#your_input_id").keypress(function(e) { if (!/[az]/i.test(String.fromCharCode(e.which))) { return false; } }); 

This will not prevent the appearance of inserted or dragged text. The best way to do this is with the change event, which fires only after the input has lost focus:

 $("#your_input_id").change(function(e) { this.value = this.value.replace(/[^az]+/gi, ""); }); 
+1
source

This worked for me, it only accepts letters without special characters or numbers

 $("#your-input-here").keypress(function (e) { return validateAlphaKeyPress(e); }); function validateAlphaKeyPress(e) { if (e.keyCode >= 97 && e.keyCode <= 122) { return true; } return false; } 
+1
source

All Articles