Converting HTML input fields to uppercase

One task which I’ve found myself implementing several times is converting data entered by a user in a form field to a canonical format, e.g. uppercase.

The jQuery for this is fairly simple:

$(function() {
  $('#text_field').keydown(function() {
    this.value = this.value.toUpperCase();

However, the downside to this approach is that the user sees the lowercase letter as they type, and then a fraction of a second later the letter is converted to uppercase as the keydown event is triggered.

Fortunately there is a quick bit of CSS which fixes the flickering problem, simply by adding the style text-transform: uppercase to the form field:

<input id="text_field" type="text" style="text-transform: uppercase">

If you use CSS alone without jQuery, then the data passed in the form will still be lowercase, even though it has been displayed in uppercase. Using jQuery and CSS together achieves the effect of updating the UI and the data processed in the form.

Of course, if it is essential that the data is converted to uppercase as part of the form processing then you should run strtoupper or its equivalent, as you cannot rely on data from the user being in the format you require.