Param-Ganak
Param-Ganak

Reputation: 5875

Is it possible to block a certain character or group of characters from entering into text box or any input field using JQUERY?

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

Upvotes: 2

Views: 5258

Answers (5)

Kevin
Kevin

Reputation: 13226

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.

Upvotes: 0

jitter
jitter

Reputation: 54605

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]/);

Upvotes: 8

Topher Fangio
Topher Fangio

Reputation: 20667

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();
    }
  }
});

Upvotes: 0

jpabluz
jpabluz

Reputation: 1312

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

Upvotes: 0

NakedBrunch
NakedBrunch

Reputation: 49413

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); 


 } 
}

Upvotes: 4

Related Questions