skip to content

HTML: Forcing INPUT text to uppercase

 Tweet Share0 Tweets

So you have a form where you want to only accept UPPER CASE text in certain input or textarea fields. There are a number of ways to tackle this ranging from JavaScript to HTML5 patterns, CSS, and server-side code. Some are really annoying.

Using JavaScript to alter text as you type

This is the most obvious and common approaches, but also the least user-friendly. On every keystroke a JavaScript event is triggered to convert the value to uppercase.

Start typing ('abc') and you'll see how it works:

Source code:

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

Aside from the distraction of seeing things change as you type, there are other problems.

Try entering 'AAA' in the input box above, select the middle 'A' and try changing it to 'ABBA'. What you end up with instead is 'ABAB', because setting the value moves the cursor to the end of the text.

Maintaining cursor position

If you move the cursor to an earlier position in the text and type, it will be bumped back to the end of the text already input. So we need some extra code to retain the cursor position:

Source code:

<input type="text" onkeyup=" var start = this.selectionStart; var end = this.selectionEnd; this.value = this.value.toUpperCase(); this.setSelectionRange(start, end); ">

So far so good, but now we're polluting the JavaScript namespace with global variables, and we have four lines of code that need to be copied to every field with an UPPERCASE requirement.

Making it modular

Rather than polluting our HTML with inline JavaScript, we create a function:

Source code:

<script type="text/javascript"> function forceInputUppercase(e) { var start = e.target.selectionStart; var end = e.target.selectionEnd; e.target.value = e.target.value.toUpperCase(); e.target.setSelectionRange(start, end); } document.getElementById("field1").addEventListener("keyup", forceInputUppercase, false); document.getElementById("field2").addEventListener("keyup", forceInputUppercase, false); </script>

Now we have a generic function which can be applied through an onload event handler and that works on both input fields as well as textareas. Only we still have that jumping effect.

Smoothing out the UX

To get around the jumping effect we can target the keypress event rather than keyup and overwrite the default action. Again there is the complication of maintaining cursor position in the input field:

Source code:

<script type="text/javascript"> function forceKeyPressUppercase(e) { var charInput = e.keyCode; if((charInput >= 97) && (charInput <= 122)) { // lowercase if(!e.ctrlKey && !e.metaKey && !e.altKEY) { // no modifier key var newChar = charInput - 32; var start = e.target.selectionStart; var end = e.target.selectionEnd; e.target.value = e.target.value.substring(0, start) + String.fromCharCode(newChar) + e.target.value.substring(end); e.target.setSelectionRange(start+1, start+1); e.preventDefault(); } } } document.getElementById("field1").addEventListener("keypress", forceKeyPressUppercase, false); document.getElementById("field2").addEventListener("keypress", forceKeyPressUppercase, false); </script>

In this new function the inner code is only executed when the keypress is a lower case character (a-z) and not accompanied by any modifier (Ctrl, Shift, Option, Alt). In that case we calculate the upper case equivalent, insert it into the correct position, then (re-)set the cursor position, and block the default action.

As an aside, in the bad old Internet Explorer days, we would actually need at least twice as much code here to handle IE quirks and limitations. Be glad we're past that.

All well and good, but what if there was a simpler approach?

CSS to the rescue

In reality it's not important if the form input is in upper or lower case. What matters is that:

  1. the user sees the text as is is going to be used; and
  2. our form handler converts the text to upper case before it is used.

With this in mind we can throw out all the preceding JavaScript and instead use a simple CSS and PHP (or equivalent back-end) solution:

Source code:

<input style="text-transform: uppercase;" type="text" name="fieldname">

Back end code:

<?PHP $_POST['fieldname'] = strtoupper($_POST['fieldname']); ?>

Do you see how much simpler things can be if you use the appropriate technology?!? A single CSS style (which can be moved to an external style sheet), plus a single line of PHP, which was probably there already. No JavaScript or jQuery required.

HTML5 Pattern Validation

As an aid to form validation we can use HTML5 input patterns to flag when an input is not valid.

In the JavaScript examples, the pattern to enforce only uppercase (assuming a single word - no spaces or punctuation) is:

<input ... pattern="[A-Z]*" ...>

But with the CSS solution your pattern also needs to encompass lower case characters as they can be accepted even if not displayed:

<input ... pattern="[a-zA-Z]*" ...>

In both cases you will need to include any non-alphanumeric characters you want to allow in the regular expression, plus any restrictions on length.

Enforcing first letter uppercase

In response to a question from Rechie in the Philippines, there is no CSS solution for forcing only the first letter in an INPUT to be uppercase.

For block elements (P, DIV) we can do it using:

<style type="text/css"> .ucfirst { text-transform: lowercase; color: blue; } .ucfirst:first-letter { text-transform: capitalize; } </style> <p class="ucfirst">first letter UPPERCASE</p>

Which outputs the folowing:

first letter UPPERCASE

But the same approach doesn't work for INPUT fields so we're back to using JavaScript.

Here's a simple example where we piggy-back off our previous forceKeyPressUppercase method and apply it conditionally according to the position of the cursor in the INPUT field:

<input id="field_ucfirst" type="text"> <script> document.getElementById("field_ucfirst").addEventListener("keypress", function(e) { if(this.selectionStart == 0) { // uppercase first letter forceKeyPressUppercase(e); } else { // lowercase other letters forceKeyPressLowercase(e); } }, false); </script>

In practice, if you are working with names, you may want to capitalize each word (e.g. "Mary Jane"), and in certain cases letters within a word (e.g. "McDonald").

In that case you need a more advanced function that uses the position and context of a letter to determine whether to make it upper- or lower-case as the user types.

< HTML

Send a message to The Art of Web:


used only for us to reply, and to display your gravatar.

<- copy the digits from the image into this box

press <Esc> or click outside this box to close

User Comments

Post your comment or question

31 October, 2018

i just want an autocapslock on first letter . how to do that ?

It's complicated, but I've added an example above.

top