I'm currently using the html5 autofocus for a login form. I am looking for a function that will autofocus the username textbox only if empty, and if not empty to autofocus on the next textbox.
2 Answers
With the HTML below
<input name="username" value="a" autofocus="autofocus">
<input name="password" type="password">
You can do something like this with jQuery
var $username = $('[name="username"]');
var $password = $('[name="password"]');
if($username.val().trim().length > 0){
$password.focus();
}
Should be that simple. Make sure Javascript is at the bottom of the page or you can use $(document).ready() function to make sure Javascript is run after HTML is rendered.
More details based on additional information
<asp:TextBox ID="UserName" runat="server" autofocus="true" required="true"></asp:TextBox>
The reason it doesn't work for your case is because you don't have an attribute called "name". I think you probably should read a little bit about jQuery selector to understand why. If you use ID, then this is how you would do it.
var $username = $('#UserName');
var $password = $('#password');
if($username.val().trim().length > 0){
$password.focus();
}
Of course you now have to match the selector for password so it will actually select password input to set the focus on.

- 3,168
- 7
- 35
- 52
-
Your example works for input boxes, but when trying to use it with an asp textbox it doesn't. Any idea why? – Nov 07 '12 at 12:52
-
What does the HTML look like? Show some example so I can give you matching answer. – juminoz Nov 07 '12 at 15:03
-
– Nov 07 '12 at 17:15
Searches the page for input fields, and forces the focus on the first empty one. We might want to restrict the fields to a given form, and possibly add textareas as well - I'll leave that up yo you though - nothing too hard.
var inputs = document.getElementsByTagName('input'),
i = -1, I = inputs.length,
curr;
for (; ++i < I;) {
curr = inputs[i];
if ( !curr.value.length ) {
curr.focus();
break;
}
}

- 15,297
- 4
- 31
- 41