How do I set the focus to the first input element in an HTML form independent from the id?
Is there a simple way to set the focus (input cursor) of a web page on the first input element (textbox, dropdownlist, ...) on loading the page without having to know the id of the element?
I would like to implement it as a common script for all my pages/forms of my web application.
Solution 1:
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.
Solution 2:
You can also try jQuery based method:
$(document).ready(function() {
$('form:first *:input[type!=hidden]:first').focus();
});
Solution 3:
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.