Click here to Skip to main content
15,886,137 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Can someone please show me how to restrict alphabets and special characters excluding '-' into a text box using jquery?
Posted
Comments
[no name] 26-Jun-14 17:12pm    
http://www.bing.com/search?q=jquery+restrict+characters
Sergey Alexandrovich Kryukov 26-Jun-14 23:44pm    
Perhaps more effective more effective approach would be looking at original jQuery documentation. It's clear where to look for — keyboard events. Please see my answer.
—SA
Sergey Alexandrovich Kryukov 26-Jun-14 23:32pm    
There are millions of correct code samples on this "problem". Honestly, answering this question again and again would not be good. Please search available CodeProject answers (as just one of the many ways to find the solution).
—SA

Please see the comments to the question by Wes Aday and myself. I could suggest one more method of finding out such solutions: read original jQuery documentation of keyboard events. In particular, pay attention how return false works on an event handler, as a blocker of default event handling: http://api.jquery.com/keypress[^].

This jsFiddle shows a complete solution: http://jsfiddle.net/ExceptionLimeCat/cmfNj[^].

—SA
 
Share this answer
 
<pre lang="cs">function allowOnlyNumber(eventInstance) {
          eventInstance = eventInstance || window.event;
          key = eventInstance.keyCode || eventInstance.which;
          if ((47 < key) && (key < 58) || key == 8 || key == 189 || key == 109) {
              return true;
          } else {
              if (eventInstance.preventDefault)
                  eventInstance.preventDefault();
              eventInstance.returnValue = false;
              return false;
          }
      }



I tried this which worked.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900