Friday, May 1, 2009

Setting Default Focus to the Correct TextBox in a Login Control

If you're using the ASP.Net Login control then your login page may look something like this:

The username, by the way, was automatically placed into the textbox via a cookie. And though it's not immediately visible in the above screenshot, the cursor is in the Password textbox via the server-side SetFocus() method. The user, upon being presented with this screen, can then just type their password and press Enter.

Now look at this next screenshot:

Not only is the cursor in the Password textbox like before, but the background color of the textbox is automatically highlighted to provide another visual cue. This highlighting was done globally with jQuery with just a few lines of code.

All good so far. But I discovered that the jQuery auto-highlighting did not work when a page was first loaded. I still do not know why but suspect that the server-side SetFocus() method does not raise the client-side 'focus' event.

Solving the problem meant moving the code the server to the client. Here's what worked for me:

<script language="javascript" type="text/javascript">
function pageLoad()

var textBoxUserName = $('#<%= Login1.FindControl("UserName").ClientID %>')[0];
if (textBoxUserName.value == "")
var textBoxPassword = $('#<%= Login1.FindControl("Password").ClientID %>')[0];

A big thanks to Dave Ward at Encosia for his invaluable help with this!

1 comment:

  1. This is good to know; You made my day :)