[javascript] 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.

This question is related to javascript html forms focus

The answer is


I needed to solve this problem for a form that is being displayed dynamically in a modal div on my page, and unfortunately autofocus isn't honored when the containing div is shown by changing the display property (at least not in Chrome). I don't like any of the solutions that require my code to infer which control I should set the focus to, because of the complications of hidden or zero-sized inputs, etc. My solution was to set the autofocus attribute on my input anyway, then set the focus in my code when I show the div:

form.querySelector('*[autofocus]').focus();

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 also need to skip any hidden inputs.

for (var i = 0; document.forms[0].elements[i].type == 'hidden'; i++);
document.forms[0].elements[i].focus();

Tried lots of the answers above and they weren't working. Found this one at: http://www.kolodvor.net/2008/01/17/set-focus-on-first-field-with-jquery/#comment-1317 Thank you Kolodvor.

$("input:text:visible:first").focus();

With AngularJS :

angular.element('#Element')[0].focus();

Tried lots of the answers above and they weren't working. Found this one at: http://www.kolodvor.net/2008/01/17/set-focus-on-first-field-with-jquery/#comment-1317 Thank you Kolodvor.

$("input:text:visible:first").focus();

You also need to skip any hidden inputs.

for (var i = 0; document.forms[0].elements[i].type == 'hidden'; i++);
document.forms[0].elements[i].focus();

You should be able to use clientHeight instead of checking for the display attribute, since a parent could be hiding this element:

function setFocus() {
    var forms = document.forms || [];
        for (var i = 0; i < forms.length; i++) {
            for (var j = 0; j < forms[i].length; j++) {
            var widget = forms[i][j];
                if ((widget && widget.domNode && widget.domNode.clientHeight > 0) && typeof widget.focus === "function")
                 && (typeof widget.disabled === "undefined" || widget.disabled === false)
                 && (typeof widget.readOnly === "undefined" || widget.readOnly === false)) {
                        widget.focus();
                        break;
                }
            }
        }
    }   
}

There's a write-up here that may be of use: Set Focus to First Input on Web Page


If you're using the Prototype JavaScript framework then you can use the focusFirstElement method:

Form.focusFirstElement(document.forms[0]);

I needed to solve this problem for a form that is being displayed dynamically in a modal div on my page, and unfortunately autofocus isn't honored when the containing div is shown by changing the display property (at least not in Chrome). I don't like any of the solutions that require my code to infer which control I should set the focus to, because of the complications of hidden or zero-sized inputs, etc. My solution was to set the autofocus attribute on my input anyway, then set the focus in my code when I show the div:

form.querySelector('*[autofocus]').focus();

You also need to skip any hidden inputs.

for (var i = 0; document.forms[0].elements[i].type == 'hidden'; i++);
document.forms[0].elements[i].focus();

There's a write-up here that may be of use: Set Focus to First Input on Web Page


The most comprehensive jQuery expression I found working is (through the help of over here)

$(document).ready(function() {
    $('input:visible:enabled:first').focus();
});

I'm using this:

$("form:first *:input,select,textarea").filter(":not([readonly='readonly']):not([disabled='disabled']):not([type='hidden'])").first().focus();

There's a write-up here that may be of use: Set Focus to First Input on Web Page


without jquery, e.g. with regular javascript:

document.querySelector('form input:not([type=hidden])').focus()

works on Safari but not Chrome 75 (april 2019)


This gets the first of any visible common input, including textareas and select boxes. This also makes sure they aren't hidden, disabled or readonly. it also allows for a target div, which I use in my software (ie, first input inside of this form).

$("input:visible:enabled:not([readonly]),textarea:visible:enabled:not([readonly]),select:visible:enabled:not([readonly])", 
    target).first().focus();

For those who use JSF2.2+ and cannot pass autofocus as an attribute without value to it, use this:

 p:autofocus="true"

And add it to the namespace p (Also often used pt. Whatever you like).

<html ... xmlns:p="http://java.sun.com/jsf/passthrough">

You also need to skip any hidden inputs.

for (var i = 0; document.forms[0].elements[i].type == 'hidden'; i++);
document.forms[0].elements[i].focus();

Putting this code at the end of your body tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.

<script>
    (function(){
        var forms = document.forms || [];
        for(var i = 0; i < forms.length; i++){
            for(var j = 0; j < forms[i].length; j++){
                if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
                    forms[i][j].focus();
                    return;
                }
            }
        }
    })();
</script>

There's a write-up here that may be of use: Set Focus to First Input on Web Page


With AngularJS :

angular.element('#Element')[0].focus();

This gets the first of any visible common input, including textareas and select boxes. This also makes sure they aren't hidden, disabled or readonly. it also allows for a target div, which I use in my software (ie, first input inside of this form).

$("input:visible:enabled:not([readonly]),textarea:visible:enabled:not([readonly]),select:visible:enabled:not([readonly])", 
    target).first().focus();

If you're using the Prototype JavaScript framework then you can use the focusFirstElement method:

Form.focusFirstElement(document.forms[0]);

This includes textareas and excludes radio buttons

$(document).ready(function() {
    var first_input = $('input[type=text]:visible:enabled:first, textarea:visible:enabled:first')[0];
    if(first_input != undefined){ first_input.focus(); }
});

Putting this code at the end of your body tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.

<script>
    (function(){
        var forms = document.forms || [];
        for(var i = 0; i < forms.length; i++){
            for(var j = 0; j < forms[i].length; j++){
                if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
                    forms[i][j].focus();
                    return;
                }
            }
        }
    })();
</script>

If you're using the Prototype JavaScript framework then you can use the focusFirstElement method:

Form.focusFirstElement(document.forms[0]);

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.


Putting this code at the end of your body tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.

<script>
    (function(){
        var forms = document.forms || [];
        for(var i = 0; i < forms.length; i++){
            for(var j = 0; j < forms[i].length; j++){
                if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
                    forms[i][j].focus();
                    return;
                }
            }
        }
    })();
</script>

Without third party libs, use something like

  const inputElements = parentElement.getElementsByTagName('input')
  if (inputChilds.length > 0) {
    inputChilds.item(0).focus();
  }

Make sure you consider all form element tags, rule out hidden/disabled ones like in other answers and so on..


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.


Putting this code at the end of your body tag will focus the first visible, non-hidden enabled element on the screen automatically. It will handle most cases I can come up with on short notice.

<script>
    (function(){
        var forms = document.forms || [];
        for(var i = 0; i < forms.length; i++){
            for(var j = 0; j < forms[i].length; j++){
                if(!forms[i][j].readonly != undefined && forms[i][j].type != "hidden" && forms[i][j].disabled != true && forms[i][j].style.display != 'none'){
                    forms[i][j].focus();
                    return;
                }
            }
        }
    })();
</script>

If you're using the Prototype JavaScript framework then you can use the focusFirstElement method:

Form.focusFirstElement(document.forms[0]);

without jquery, e.g. with regular javascript:

document.querySelector('form input:not([type=hidden])').focus()

works on Safari but not Chrome 75 (april 2019)


The most comprehensive jQuery expression I found working is (through the help of over here)

$(document).ready(function() {
    $('input:visible:enabled:first').focus();
});

You should be able to use clientHeight instead of checking for the display attribute, since a parent could be hiding this element:

function setFocus() {
    var forms = document.forms || [];
        for (var i = 0; i < forms.length; i++) {
            for (var j = 0; j < forms[i].length; j++) {
            var widget = forms[i][j];
                if ((widget && widget.domNode && widget.domNode.clientHeight > 0) && typeof widget.focus === "function")
                 && (typeof widget.disabled === "undefined" || widget.disabled === false)
                 && (typeof widget.readOnly === "undefined" || widget.readOnly === false)) {
                        widget.focus();
                        break;
                }
            }
        }
    }   
}

I'm using this:

$("form:first *:input,select,textarea").filter(":not([readonly='readonly']):not([disabled='disabled']):not([type='hidden'])").first().focus();

Without third party libs, use something like

  const inputElements = parentElement.getElementsByTagName('input')
  if (inputChilds.length > 0) {
    inputChilds.item(0).focus();
  }

Make sure you consider all form element tags, rule out hidden/disabled ones like in other answers and so on..


This includes textareas and excludes radio buttons

$(document).ready(function() {
    var first_input = $('input[type=text]:visible:enabled:first, textarea:visible:enabled:first')[0];
    if(first_input != undefined){ first_input.focus(); }
});

For those who use JSF2.2+ and cannot pass autofocus as an attribute without value to it, use this:

 p:autofocus="true"

And add it to the namespace p (Also often used pt. Whatever you like).

<html ... xmlns:p="http://java.sun.com/jsf/passthrough">

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to focus

How to remove focus from input field in jQuery? Set element focus in angular way Bootstrap button - remove outline on Chrome OS X How can I set focus on an element in an HTML form using JavaScript? Set Focus on EditText Mobile Safari: Javascript focus() method on inputfield only works with click? Correct way to focus an element in Selenium WebDriver using Java Prevent the keyboard from displaying on activity start What are some reasons for jquery .focus() not working? How can I set the focus (and display the keyboard) on my EditText programmatically