views:

105

answers:

4

How do I achieve this:-
When user types character like 'abcd' and then '>'(an invalid character for my application), I want to set the text back to 'abcd'. Better if we can cancel the input itself as we do in winforms application. This should happen when user is typing and not on a click of button.

I want this to be applied on all text boxes in my web page. This will be easy if the solution is jQuery based. May be something which will start like this.
$("input[type='text']")

SOLUTION
I used both of the answer provided by @jAndy and @Iacopo (Sorry, couldn't mark as answer to both) as below.

$(document).ready(function() {
  //makes sure that user cannot enter < or > sign in text boxes.
  $("input:text").keyup(purgeInvalidChars)
      .blur(purgeInvalidChars)
      .bind('keypress', function(event) {
        if (event.which === 62 || event.which === 60)
          return (false);
      });
  function purgeInvalidChars() {
    if (this.value != this.value.replace(/[<>]/g, '')) {
      this.value = this.value.replace(/[<>]/g, '');
    }
  }
});

Though one issue still remained i.e. It doesn't allow user to select text in the textbox and this only happens on chrome, work fine on IE (for the first time :D), not tested on firefox. It would be glad if anyone can find solution for that or hope people at Google solves it :D.

UPDATE
I solved it by if (this.value != this.value.replace(/[<>]/g, '')) check. Also updated solution.

Thanks again to all the answerers.

+2  A: 

use this

Reigel
That works pretty well and I don't see a reason to reinvent the wheel.
ryanulit
It is throwing exception: `Uncaught TypeError: Object #<an Object> has no method 'charCodeAt'`
Ismail
@ryanulit: I'd not include like **15kb** (lots of code), for something that one can be solved with 4 lines.
jAndy
This is what I've written within ready function and it throws the above error. `$("input:text").numeric({ ichars: "<>" });`
Ismail
I agree with jAndy though its not 15kb :).the packed version is 1.55kb
Ismail
Oh right, they put whole jquery into that zip. Anyways overkill :)
jAndy
Packed version in the sense reduced one, which doesn't contain much of the white space characters.
Ismail
+1  A: 

Example (keypress):

$(document).ready(function(){
    $('input:text').bind('keypress', function(event){

    if(event.which === 62 || event.which === 60)
       return(false);
    });
});​

Example (keydown):

$(document).ready(function(){
  $('input:text').bind('keydown', function(event){
    if(event.which === 226)
       return(false);
  });
});​

Just make use of the preventDefault and stopPropagation functions for events. Those are triggered by returning (false) within an event handler.

In this example, I just check for the keycode of < and > which is thankfully on the same key. If we hit that code, we just prevent the default behavior.

Reference: .preventDefault(), .stopPropagation()

jAndy
Not sure what you were testing on but this does not work at all on a Windows machine, and the keycode of the < is 188 and 190 for >. Also, browser I used was chrome.
ryanulit
@ryanulit: using winXP on chrome. for `keydown` it is 226 for me, both `which` and `keyCode`. No reason to downvote this.
jAndy
this also not working I'm able to enter `<` and `>` characters. I'm using win7
Ismail
@Ismail: try the keypress variant
jAndy
Keypress variant works perfectly. :). Thank you v v much @jAndy
Ismail
@Ismail: yepa, there is really no need to bump your site with some plugin just for an easy task like that.
jAndy
100% agreed!!!!!!!!
Ismail
Will it work on other OSes than win7?
Ismail
@Ismail: `which` is normalized through jQuery, so it should work cross-browser, cross-plattform for `keypress`.
jAndy
Ok. Thank you very much.
Ismail
A: 
$('#textBox').keyup(function(e){
            var myText = $('#textBox').val(); 
            myText =  myText.replace(">", "");
            myText =  myText.replace("<", "");
            $('#textBox').val(myText);
        });

-- Update --

keyup instead keypress

Mithun P
that is like.. boyohboy of overkill
jAndy
I don't know why this would be downvoted. It is not the most efficient implementation, but it is a correct solution.
patrick dw
This doesn't work @Mithun
Ismail
I see the issue. You would need to change it to `keyup` instead of `keypress`.
patrick dw
@patrick you are right
Mithun P
+2  A: 

You should catch the 'keyup' and 'blur' events and attach them to a function that bonifies the input: don't forget that the user can paste an invalid sequence of characters.

So for example

$('input[type="text"]').keyup(purgeInvalidChars).blur(purgeInvalidChars)

function purgeInvalidChars()
{
   this.value = this.value.replace(/[<>]/g, ''); 
} 

surely you will improve the regexp, maybe replacing all characters except the enabled ones.

Sorry, I can't test my code, so you should take it cum grano salis :-)

Iacopo
@lacopo - This works, except that you should add the `g` global identifier to the regex just in case someone does a copy/paste with more than one invalid character.
patrick dw
edited, thanks!
Iacopo
Thanks for pointing out the paste thing. I had missed it completely This works but user is not able to select the text in the text box. Can anything be done for that?
Ismail
Yes, you should avoid to replace the text if `event.which` is not a real character (i.e. it is an arrow, or Home etc.)
Iacopo
Can you update it in your answer?
Ismail