Click here to Skip to main content
16,013,338 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello...
I have a html textbox. I want to allow only predefine charecter in textbox by javascript.

C#
<input type="text" id="txt1"  onkeypress="allowChar(this, 'ABC123');" />


Here an example of textbox. In which allow only capital A, capital B, capital C and in numeric only 1,2,3.

C#
<script type="text/javascript>
function allowChar(txt, char)
{
  ........
  ........
  ........
}
</script>


Please solve this problem by javascript or jquery as you wish.


Thanks
Regards
Rakesh
Posted
Updated 5-May-13 20:52pm
v5
Comments
_Amy 6-May-13 2:50am    
You are missing return statement in your HTML. While calling a javascript function you must use return statement.

You are already passing Textbox Object and Your Predefined Chars to your function. Match the chars there with key codes[^]. Try this:
HTML:
HTML
<input type="text" id="txt1" class="customChar" önkeypress="return allowChar(this, 'ABC123');" />

JavaScript:
JavaScript
function allowChar(textbox, chars){
    //check with key code here
    var keynum;
    if(window.event){ // IE					
    	keynum = e.keyCode;
    }else
        if(e.which){ // Netscape/Firefox/Opera					
    		keynum = e.which;
         }
    var EnteredWord = String.fromCharCode(keynum); //Here you got your pressed key    
    //If matching with the predefined characters stored in 'chars' then return true otherwise return false.
}



Hope it helps!
--Amit
 
Share this answer
 
v2
Comments
Rakesh Tailor 6-May-13 2:59am    
thanks for support.
I can find out keycode of enter charecter in textbox.
But how I get keycode of 'ABC123'.
Because these charecters in a string not a single char.
_Amy 6-May-13 3:17am    
I think you didn't see my updated answer. EnteredWord variable is storing the current pressed key(Not keycode, keycode is already converted to word). Now loop through the predefined chars, if matches return true otherwise return false.

--Amit
 
Share this answer
 
v2
Google is your friend: Be nice and visit him often. He can answer questions a lot more quickly than posting them here...

A very quick search gave 200,000 hits: "javascript restrict textbox"[^]

In future, please try to do at least basic research yourself, and not waste your time or ours.
 
Share this answer
 
Comments
Rakesh Tailor 6-May-13 3:03am    
what your think that I am not trying to my self.
If you feel that you are wasting your time to help to other then please don't answer anyone.
OriginalGriff 6-May-13 3:18am    
No, I feel that you are wasting the time of everyone else because you are too lazy to do something yourself.
Thanks7872 6-May-13 3:22am    
@OrginalGriff: Agreed.

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