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.

有帮助吗?

解决方案

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.

其他提示

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;
    }
}​
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top