tags:

views:

95

answers:

5

Hello friends!

I have a text input field like text box or text area. I want to prevent the user from entering certain character or a group of characters. That is for example if I dont want # * @ and numbers from 0-9 these characters. So Whenever user press any of the above character key then that character should not appear in to an input field. It means directly blocking that character.

Is this possible in Jquery? Please give me some guidelines to achive it.

Thank You

+2  A: 

The following will allow only alpha characters in a text box with the ID "myTextBoxID".

$("#myTextBoxID").bind("keypress", function(evt) 
    { 
        var charCode = (evt.which) ? evt.which : window.event.keyCode;  

        if (charCode <= 13) 
        { 
            return true; 
        } 
        else 
        { 
            var keyChar = String.fromCharCode(charCode); 
            var re = /[a-zA-Z]/ 
            return re.test(keyChar); 


 } 
}
Alison
Hi friend! Your solution is working good. Can you explain the code please? It will help me to understand its working.
Param-Ganak
A: 

You could try

$('#formelement').keyup(function(event) {
   clean_text = // javascript regex, replace [^a-zA-Z]
   $('#formelement').attr('value', clean_text);
});

Can't test this at the moment though.

Kevin
A: 

Using the onChange event and after that, calling a function that will check if the key is one of the keys you want to remove, just erase the last character.

You should remember that if a key is hold, it will write several times, and if you are only using keyUp, keyDown or keyPress, you will still get the other characters that were repeated (Unless you erase all the undesired chars from the textfield - Which if long could diminish performance)

http://www.w3schools.com/jsref/event_onchange.asp

jpabluz
A: 

You can capture the current key presses by using the jQuery keypress method.

I would suggest something akin to the following psudocode:

var is_capturing = false;

$('#my_input').focusin(function() {
  is_capturing = true;
}).focusout(function() {
  is_capturing = false;
}).keypress(function(event) {
  if (is_capturing) {
    if (event.keyCode == <<the keycode you want to capture>>) {
      event.preventDefault();
    }
  }
});
Topher Fangio
+6  A: 

jquery-keyfilter

This plugin filters keyboard input by specified regular expression.

e.g. so just specify what you don't want

$("#yourinput").keyfilter(/[^#\*@0-9]/);
jitter
Wow, nice find. Excellent plugin!
Kevin