Javascript – How to set the focus to the first input element in an HTML form independent from the id

focusformshtmljavascript

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.

Best Answer

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.