Skip to content
A. P. Barratt
Professional Geek, Author of Evil Dr. Eye webcomic and The Hudud Trilogy, Front End Developer.
  • Blog
  • The Hudud Trilogy (novels)
  • Evil Dr. Eye (webcomic)
  • Geek Scot
  • Who is A. P. Barratt?
  • Twitter
  • Facebook

Set default field (focus) on ASP.NET Login Control

Posted on 3rd August 2012Author apbarratt

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.

Post navigation

Previous Article Previous Article: Graduation Garden Party
Next Article Next Article: How to block Farmville 2 Notifications on Facebook

Published byapbarratt

I own this here website, bow down before your God! View all posts by apbarratt

Tags: asp login control, ASP.NET, control, default field, default focus, default textbox, text box
Categories: ASP.NET, HTML & CSS, javascript
Copyright © 2019 Your Name. All rights reserved.