ASP.Net/JavaScript to upper case a text input field onblur

Posted: 08/27/2012

The following JavaScript will upper case the text in an input field when the focus goes away from that field. I will include both the JavaScript as it’s used with standard HTML elements and then the vb.net and c# code to add it as an attribute to a TextBox control. I know this is kinda circa 2003 but I still find it useful from time to time.

HTML/JavaScript

    <input type='text' id='textBox' onblur='this.value = this.value.toUpperCase();'>

VB.Net

    TextBox1.Attributes.Add("onblur", "this.value = this.value.toUpperCase();")

C#

    TextBox1.Attributes.Add("onblur", "this.value = this.value.toUpperCase();");

With the versions for ASP.NET you may want to put a check on so that it only adds this attribute in if it’s not a PostBack to the page. In the page load, it would look something like this:

VB.Net

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If IsPostBack = False Then
            TextBox1.Attributes.Add("onblur", "this.value = this.value.toUpperCase();")
        End If

    End Sub

I have seen multiple solutions that encourage the use of CSS to update the value via “text-transform: uppercase”. Beware of this solution. This will update the value on the screen to display as upper case, but when it’s posted to the server it will be posted however the user typed it (lower case for instance, even though it didn’t display on the users screen like that). If you use this, it will require you to somehow update the value posted (which is more trouble than it’s worth when the above works fine with a single line of code, in my opinion).