How do I set the focus to the first input element in an HTML form independent from the id?
Although this doesn't answer the question (requiring a common script), I though it might be useful for others to know that HTML5 introduces the 'autofocus' attribute:
<form>
<input type="text" name="username" autofocus>
<input type="password" name="password">
<input type="submit" value="Login">
</form>
Dive in to HTML5 has more information.
You can also try jQuery based method:
$(document).ready(function() {
$('form:first *:input[type!=hidden]:first').focus();
});
document.forms[0].elements[0].focus();
This can be refined using a loop to eg. not focus certain types of field, disabled fields and so on. Better may be to add a class="autofocus" to the field you actually do want focused, and loop over forms[i].elements[j] looking for that className.
Anyhow: it's not normally a good idea to do this on every page. When you focus an input the user loses the ability to eg. scroll the page from the keyboard. If unexpected, this can be annoying, so only auto-focus when you're pretty sure that using the form field is going to be what the user wants to do. ie. if you're Google.