HTML: Forcing INPUT text to uppercase
Start typing ('abc') and you'll see how it works:
<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:
<input type="text" onkeyup=" var start = this.selectionStart; var end = this.selectionEnd; this.value = this.value.toUpperCase(); this.setSelectionRange(start, end); ">
Making it modular
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:
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:
- the user sees the text as is is going to be used; and
- our form handler converts the text to upper case before it is used.
<input style="text-transform: uppercase;" type="text" name="fieldname">
Back end code:
<?PHP $_POST['fieldname'] = strtoupper($_POST['fieldname']); ?>
As an aid to form validation we can use HTML5 input patterns to flag when an input is not valid.
<input ... pattern="[A-Z0-9]*" ...>
But with the CSS solution your pattern also needs to encompass lower case characters:
<input ... pattern="[a-zA-Z0-9]*" ...>
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.
Related Articles - Text Manipulation
Send a message to The Art of Web:
press <Esc> or click outside this box to close