Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

format textbox

Status
Not open for further replies.

taoist

Programmer
Joined
Feb 1, 2006
Messages
35
Location
US
how can I setup a textbox to only allow capital letters input into the textbox?

Also can I setup a textbox to only allow certain letters typed into the box

right now I the textbox is set to 1 Max Chars and 1 Char Width

any help would be greatly appreciated
 
Use an onkeyup event in the textbox to call a function.
In the function get the value of the text box and test the last character entered to whatever criteria you have. If the character fails then remove it from the string and write it back to the text field. Then test to see if with the new character the length of the string has reached max.



Stamp out, eliminate and abolish redundancy!
 
I'm new at jaascript

do you have a sample script
 
Here is a quick and dirty (been saying that a lot lately) sample.
There is an inherant problem in that people can type faster than javascript can execute the function so they can enter several characters very quickly so my code is checking the entire string, not just the last character entered.
It first tests for the length and if it exceeds the maximum then it trims the value back and updates the text box.
Then it tests to make certain that the text in the field consists ONLY of capital letters. That code can be modified if you want to include numbers or characters like a hyphen or underscores, etc.
The problem with this test is that if someone enters an invalid character it pops up an alert but it does not remove the character. From that point forward every character they type will cause another alert until the invalid one is removed.

There are ways around this such as looping through and testing all of the characters individually and removing them if they do not belong but that is much slower meaning they can type even further ahead of the script but also confusing to the person typing if they are not watching and parts of what they thought they typed just disappeard.

The approach really has a lot to do with what you want to accomplish. It might be better to let them type what they will and then test the field afterwards reporting any mistakes back to them. It is certainly a lot smoother to do it that way.

Another approach that might work is to trap the keypresses on the entire page and if the keypress occurs while the focus is on your field then you test it and let it complete or stop it before the text is entered. I have never done this though I am sure someone else here must have.

In any event, this is a sample to show you one possible approach. It will certainly need work but it all depends on your exact goals so this is more informative than an actual solution.
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[URL unfurl="true"]http://www.w3.org/TR/html4/loose.dtd">[/URL]
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Form Test</title>
<SCRIPT type="text/javascript">
function checkvalue(fldname)
{ //Set a maximum length for string
  var maxlen = 5;
  if (fldname.value.length > maxlen)
  { //If value is greater than maximum length trim it.
    fldname.value = fldname.value.substring(0,maxlen);
  }
  //Test to make sure string contains only capital letters.
  if (!alpha_only(fldname.value))
  {
    alert("Invalid character");
  }
}

function alpha_only(value)
{ //Only allows capital letters.  No numbers or symbols.
  var re = /^[A-Z]*$/;
  return re.test(value);
}
</SCRIPT>
</head>
<body>
  <input type="text" name="myText" id="myText" onkeyup="checkvalue(this);">
</body>
</html>

Code:
Stamp out, eliminate and abolish redundancy!
 
I think the best way to do this would be to detect the character code of each character as it is typed, and return an uppercase version.

This way, you avoid the need to set the "value" attribute, which has repercussions. For example, when setting "value", a lot of browsers will move the caret (text cursor, also commonly, but wrongly called "carrot") to the end of the text field. This would not be desirable if editing text in the middle of the field.

Modifying the character code typed (if this is at all possible) would avoid this.

Hope this helps,
Dan

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
I began working on exactly that yesterday Dan. It is certainly possible though I had to jump through some hoops to get it working smoothly and key trapping is not standard across browsers.
There is also the problem that you can type faster than javascript can respond to the onchange event in the code above so it could miss checking some characters and if you paste into the field it misses all of them if you trap just by event.

I tried setting up a page event to trap key presses with the onkeypress event but unfortunately IE browsers will not trap non alpha-numeric keys when the focus is within an input field so it could not trap the control key. If focus was on the body of the page it would trap it but not within an input. Instead I used an onkeydown event to start trapping and tested for the CTRL key value rather than the ctrl-V value and if detected it does a blur() against the field being tested which cancels the onkeyup event from occuring. If a legitimate character is detected it lets it through. Works pretty well in both IE and Firefox. Care to test in Netscape or Opera for me? I do not have those installed at the moment.

My next step is to setup a method to convert the character code into an ascii value for testing rather than doing a 1-1 comparison for every non-allowable character and using parameters to indicate what type of testing to do so all of the test code can be isolated and re-used in different combinations just by passing parameters from each field you want testing done on.

Try this code, I would like to know if you see any methods of improvement. The one thing I have not been able to do yet is to get the focus to go BACK to the proper field if a CTRL key is pressed.

Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">

<html>
<head>

<SCRIPT type="text/JavaScript">
<!--

var whichfld='';
function keycheck(e,which)
{
  var nav4 = window.Event ? true : false;
  whichfld=which;
  var failed=false;
  if (nav4) // Navigator 4.0x
    var whichCode = e.which
  else // Internet Explorer 4.0x
    if (e.type == "keydown") // the user entered a character
      var whichCode = e.keyCode
    else
      var whichCode = e.button;

  if (whichCode == 17)
  {
    document.getElementById(which).blur();
    failed=true;
  }
  if (failed)
    return false;
  return true;
}

// -->
</SCRIPT>

</head>
<body>

<FORM NAME="keys">
<input type="text" id="myText" onKeyDown="return keycheck(event,this.id);">

</FORM>

</body>
</html>

Stamp out, eliminate and abolish redundancy!
 
This code here works great with changing text to upper case

with this code how could prevent certain text to be entered into the textbox.


<script language="JavaScript">
function toUpper(e,r){

r.value = r.value.toUpperCase();

}
</script
 
taoist, I am working out some problems with the code above.
Using onkeydown to trap the key press allows me to cancel CTRL key presses so they cannot paste into the field but it does not allow me to get the actual character entered into the field. onkeypress returns the actual value 65 for an upper case A and 97 for lowercase but onkeydown and onkeyup will always return the uppercase value even though they allow the lower case letter to populate the box when the event is done. Consequently I cannot TEST the value to see if it is upper or lower case.

I am working on a few possible solutions but it will take some time.


Stamp out, eliminate and abolish redundancy!
 
Ya know Taoist, this is really not an easy thing to do.
I came with code for it but nothing is going to be perfect.

The code below traps every keypress inside a field you setup for testing. You can pass parameters to the keytest function to tell it what it should and should not allow to be typed into that field. The parameters consist of the names of the functions to call for each type of test.
If any test fails then the keypress is aborted and the character never gets written to the field.

There is a drawback to this method. There is no direct way to trap the Ctrl key when in a form field (at least in IE) so if the user pastes data into the field with Ctrl-V the data is NOT tested in the keytest function. To counter this problem I used an onkeyup function also. The code tracks the last known valid value of the field and when onkeyup occurs it executes the followup function.
The followup function checks to see if there is a difference between what the length of the data was when the keypress event occured and what it is now and if it finds a discrepency it resets the field to the previous value.

Currently the code does not test if the client uses the mouse button to right-click/paste or the browser doing edit/paste into the field. That should be possible to add in but I do not have time at the moment to work on it.

I have one test function called AZ indicating only capital letters from A to Z. It blocks anything else from being entered. To add more tests you create a function for each type of test and add the function name without quotes around it to the onkeypress event parameters.
This way you can set different tests for every field and different numbers of tests as well.

You stated you wanted to only allow capital letters and this code prevents the typing of them. It does not convert the case of the letter typed. If you want to convert characters then you would not filter out the lowercase letters in the keytest function, you would add the conversion code to the bottom of the followup function. Or better yet you alter the function to accept parameters like keytest does and pass the function calls into followup just like they are done in keytest.

Sorry if this is confusing, it is a complicated method to explain. Play around with it and you will learn and perhaps come up with something more to your specific needs.

Here is the code:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Trap Keypress events and block unwanted characters</title>
<SCRIPT type="text/JavaScript">
<!--

var failed;
var lastval='';
function keytest(e)
{
  failed=false;
  whichfld=window.event.srcElement.id; //Get object of element being tested
  lastval=document.getElementById(whichfld).value; //Set global variable to current value of field.
  var character = String.fromCharCode(event.keyCode); //Convert keyCode value to ascii character.

  for (var x=1;x<arguments.length;x++)
  { //Loop through arguments passed to function and execute each testing function.
    var func=arguments[x];
    var status=func(character);
    if (!status)
      failed=true; //Set failed flag so keypress event is canceled and character not written.
  }
  if (failed)
    event.returnValue = false;
}

function followup(which)
{ //If client used a Ctrl-V to pass info into field this will strip anything pasted in.
  var curval = document.getElementById(which).value;
  if (curval.length > lastval.length+1)
    document.getElementById(which).value = lastval;
  lastval=document.getElementById(which).value;
}

function AZ(value) //Only allow capital letters.  No numbers or symbols.
{ //Only allows capital letters.  No numbers or symbols.
  var re = /^[A-Z]*$/;
  return re.test(value);
}

// -->
</SCRIPT>
</head>
<body>
<FORM NAME="KeyTest">
<input type="text" id="myText" onkeypress="keytest(event,AZ);" onkeyup="followup(this.id)" onfocus="lastval=this.value;">
<br><br>
<input type="text" id="myText2" onkeypress="keytest(event,AZ);" onkeyup="followup(this.id)" onfocus="lastval=this.value;">
</FORM>
</body>
</html>

Stamp out, eliminate and abolish redundancy!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top