Click Link Sets Focus on Input

How can I make it so that when I click a link, my input box now has a cursor / focus set?

<a href=“javascript:document.getElementbyId(‘fieldId’).focus()”>focus the field</a>

Here’s a more flexible way to do that, without messing up your HTML code.

Here’s a link that references the field.


<a id="login" href="#username">Login</a>
...
<input id="username" name="username">

The above is guaranteed to at least partially work even when JavaScript is not available. Bonus!

Attach an onclick event to the link:


document.getElementById('login').onclick = function () {
    ...
};

and in the function, set the focus to the href target:


... = function () {
    var id = this.href.split('#')[1];
    document.getElementById(id).focus();
    return false;
};