views:

54

answers:

3

Hi there ... am wondering ... how to only accept alphabetical pressed keys from the keyboard .. i am using the jQuery .keypress method ... now i wanna know how to filter the passed key ...

i am trying to build a simple autocomplete plugin for jQuery ...i know a about jQuery UI, but i want to do it myself ...

thanks in advance :)

+1  A: 

In your callback, you can check the event's keyCode property. If you want to disallow the key being entered, simply return false. For example:

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

Note that this won't really work very well. The user could still paste in other text, or use a mouse-based entry device, or any number of other things.

I've edited this based on Tim Down's comment and replaced keyCode with which, which is correct across keydown, keyup, and keypress events.

Ian Henry
The function name is wrong: it's `keypress`. Also, `keyCode` is the wrong property. It is only loosely related to the actual character typed. In jQuery, you want `which`, which normalizes different properties required in different browsers.
Tim Down
that solves the problem ... thanks very much
Dewan159
+1  A: 

You can bind a function to the field that replaces anything that's not in the a-z range.

<input name="lorem" class="alphaonly" />

<script type="text/javascript">
$('.alphaonly').bind('keyup blur',function(){ 
    $(this).val( $(this).val().replace(/[^a-z]/g,'') );
});
</script>

Source: random Google result

Alec
+1  A: 

The following will prevent any character typed outside of a-z and A-Z from registering.

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

This won't prevent pasted or dragged text appearing. The surest way to do that is the change event, which is only fired once the input has lost the focus:

$("#your_input_id").change(function(e) {
    this.value = this.value.replace(/[^a-z]+/gi, "");
});
Tim Down
You're missing a close paren in your `if` for `keypress`! It should be: `if (!/[a-z]/i.test(String.fromCharCode(e.which))) {`
Peter Ajtai
@Peter: Thanks. Fixed now.
Tim Down