0

I am building a web app. I believe it will be easiest if I try to explain what I want the user experience to look like before I ask my question.

I want my user to go on my site and begin to type in a text field. When each character is inputted, I want to run a conditional statement on that character to decided if it should be added to the text field. If the character inputted is not one I want, the character isn't added.

I have validations in my model to do this after the text is submited, but I want it to be real time. I'm guessing this relates to JavaScript and I am not comfortable enough in coding it to know what to search for/research. Can you assist me in where to look (Tutorials, Concepts, etc)?

Thank you for taking the time to read this.

PinnyM
  • 35,165
  • 3
  • 73
  • 81
kruptos
  • 15
  • 5
  • Removing references to Ruby on Rails - this question is specific to JavaScript. – PinnyM Aug 08 '13 at 00:27
  • This may help you, although it uses jQuery to do this a bit more efficiently - http://blog.troygrosfield.com/2010/12/01/preventing-character-input-using-javascript/ – PinnyM Aug 08 '13 at 00:29

2 Answers2

0

It's not precisely your situation but a very good starting point would be this question and its answers: How to allow only numeric (0-9) in HTML inputbox using jQuery?

You are basically looking for javascript that will intercept the keypress and only allow it if it is an allowed key, the question above implements this for numeric keys - start with that and expand it as per your needs.

Community
  • 1
  • 1
Matt
  • 13,948
  • 6
  • 44
  • 68
0

You can do this with the preventDefault method on the event object passed to the keydown event. This basically tells the browser to not preform its default action (which on a text field would be appending the letter to the field).

Here is an implementation using jQuery for brevity, but you can implement the same functionality in pure javascript as well:

$('input').on('keydown', function(event) {
    // event.which is the character code
    if ( /* some condition */ ) event.preventDefault();
});

And here is a fiddle with an example where you cannot type the letter A: http://jsfiddle.net/354XJ/

Alex D
  • 189
  • 4