I have been struggling with something at work for a few days now and that is setting the default text field on the login page of the miiCard website.

Our login page is very simple, username, password, that’s it.  Choosing to have one field as selected proved very tricky because we were using the asp:Login control which did not provide easy access from the code behind and refused to allow a static ID to be used by javascript/jquery.

Eventually, I worked out a decent solution using jQuery (though the same could be applied to native javascript.

The trick was to put at the bottom of my login page markup some jquery mixed with some javascript.  We knew that there is a TextBox control with the server ID “UserName” inside the Login control which had the server ID “Login1″.

So the JQuery was quite simply, one line.

<script type="text/javascript">
    $(‘#<%= ((TextBox)Login1.FindControl("UserName")).ClientID %>’).focus();
</script>

Which generates the correct code replacing thepart with the client ID that the server had generated.

I haven’t tested this but the same should be easy to do if you’re not using JQuery too.

<script type="text/javascript">
    document.getElementById(‘<%= ((TextBox)Login1.FindControl("UserName")).ClientID %>’).focus()
</script>

Remember that JQuery requires the # to specify that it’s an ID where as Javascript already knows it’s dealing with an ID so no # is required.

Hope this of interest to someone.