Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 472
splattne Avatar asked Nov 10 '08 10:11

splattne


People also ask

How do you set focus on a specific element in HTML?

To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.

Does autofocus attribute always set focus on first input field in html5?

The first input or textarea in source order that has the autofocus attribute will be focused on page load. In browsers without autofocus support, no fields will be focused on page load, unless otherwise given focus with JavaScript.


2 Answers

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.

like image 75
Jacob Stanley Avatar answered Oct 16 '22 13:10

Jacob Stanley


You can also try jQuery based method:

$(document).ready(function() {     $('form:first *:input[type!=hidden]:first').focus(); }); 
like image 39
Marko Dumic Avatar answered Oct 16 '22 12:10

Marko Dumic