Convert input text to uppercase as user types

Hi all, this should be quite simple but cant quite figure out how to do this. As the user types i want to convert the text to uppercase

how might i go about this, i think using a onkeyup function on the input. What about the function tho, dont really know where to start??

<input onkeyup="convertToUppercase(this)"/>

any suggestions / solutions would be very greatful :slight_smile:

Try this.

function convertToUppercase(el) {
  if(!el || !el.value) return;
  el.value = el.value.toUpperCase();
}

It’s best to avoid using inline event handlers. I suggest you read these:
The Behavior Layer
Separating behavior and structure
Behavioral Separation
Unobtrusive JavaScript
DOM Scripting - Sample chapter: Best Practices
Accessible DHTML

This works in Opera, Firefox and Internet Explorer:

  
<style type="text/css">
.bigLetter { text-transform: uppercase; }
</style>
</head>
<body>
<input type="text" class="bigLetter">


This worked on ie,opera and firefox.

  
<input type="text"  onkeyup="this.value=this.value.toUpperCase()"/> 

This worked on Internet Explorer, Firefox. It don’t work on Opera >


<input type="text" onkeyup="this.style.textTransform='uppercase'"/>

Using textTransform for this is silly. It displays the text as uppercase, but it doesn’t actually change the case of the characters.

Assigning to this.value moves caret to end of input, which is unacceptable. Using “text-transform” is nice and clean, the actual conversion should be done on the server side in any case.

Oh, right. I forgot about that side effect. Thanks stereofrog. :slight_smile: It’s good to have someone here who can catch when I forget an important detail. And you’re right that you should do it server-side in case the JavaScript didn’t execute for whatever reason.

Many sites do this via onchange or onblur, so that the side effect isn’t a problem.


<script type="text/javascript">

function show(a){

var el= document.getElementById(a);
alert(el.value);

}

</script>

<style type="text/css">
.bigLetter { text-transform: uppercase; }
</style>

<input type="text" id="t1" onkeyup="this.value=this.value.toUpperCase(); show(this.id)" ;/> Message box displays E on Internet Explorer, Opera and Firefox  <br>

<input type="text" id="t2"  onkeyup="this.style.textTransform='uppercase'; show(this.id)"/>Message box displays e on Opera, Firefox and Internet Explorer.<br>

<input type="text" id="t3"  onkeyup="show(this.id)" class="bigLetter"> Message box displays e on Opera, Firefox and Internet Explorer.