View Full Version : JavaScript change individual characters to upper case

08-15-2008, 12:52 PM

I want to type into a HTML text box so that after each character is entered, a JavaScript function will raise the character to upper case and after doing so the cursor position will remain after the character entered ready for the next character, if that makes sense, just the same as typing say into a Word document, but each time a letter is entered it is immediately upper cased. Problem with my code is that after the .toUpperCase() method the cursor leapes over to the end of the line, which is unsatisfactory. I don't want to use the onblur event to do the job instead the change needs to be dynamic as I type. For example text contains "FRED SMITH", I want to the position cursor in the space and enter in a middle name, which may be typed in lowercase, but end up with: "FRED MICHAEL SMITH". Any ideas please?

<input id='txt1' value='FRED SMITH' onkeyup='txt1_onkeyup()'>
<script language='javascript'>
function txt1_onkeyup()
event.keyCode == 35 ||
event.keyCode == 36 ||
event.keyCode == 37 ||
event.keyCode == 39
) // ignore cursor keys.
if (event.keyCode != 8)
var o=document.all;
o.txt1.value = o.txt1.value.toUpperCase();

08-15-2008, 01:00 PM
How about applying a style of text-transform: uppercase; (http://www.w3schools.com/Css/pr_text_text-transform.asp) to your input element?

Philip M
08-15-2008, 01:10 PM
Enter your first name: <input type="text" id="firstname" style="text-transform:uppercase"><br>
Enter your family name: <input type="text" id="familyname" style="text-transform:uppercase"><br>
Enter your dog's name: <input type="text" id="dogsname" style="text-transform:uppercase">

Instructions on a Swedish chainsaw -- "Do not attempt to stop chain with your hands or genitals."