How do I set the focus to the first input element in an HTML form independent from the id?
Asked Answered
K

19

102

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.

Kipper answered 10/11, 2008 at 10:30 Comment(3)
REMARK if form is placed down in page in a way user has to scroll down page to see the form,by setting the focus will automatically scroll down the page like an anchor would do. This is not very good cause the user getting to such page would see it immediately scrolled down to the form position. I tested on Safari and FF (IE7 does not perform the page scrolling).Tavis
@Marco_Demaio My web app is structured in a way that every page has its input boxes near the top of the window.Kipper
what if the user resized the browser window height to something smaller than 768px. Page would scroll to the where you set focus. Anyway I wanted only to warn you in case you did not know about such minor issue, I didn't know about it either before doing some tests.Tavis
T
104

You can also try jQuery based method:

$(document).ready(function() {
    $('form:first *:input[type!=hidden]:first').focus();
});
Towage answered 10/11, 2008 at 21:1 Comment(7)
It Works! I'm starting to integrate jQuery in my web application. So, I think I will stick with this approach! Many thanks, Marko!Kipper
What happens if the first form on the page is hidden in this case? Or if the first element on the form is hidden via CSS? Surely this would fail. I am being pedantic of course but that's how I roll.Redtop
In my case (using ASP.NET) I have just ONE form which is never hidden. So this works for me.Kipper
@Jame Hughes, you can write it as a function and call it when u need it, and you can make exceptions. For me this solution really helped.Bukavu
this is not working for me for some reason. shouldn't I see a cursor.Astromancy
@AdonisSMU Please, paste your HTML somewhere.Towage
This slightly simpler version should suffice: $(':input[type!=hidden]:first').focus()Harmful
G
164

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.

Gaullism answered 22/6, 2011 at 20:49 Comment(5)
autofocus is the attributename . What about its value ?Somethig like autofocus=true not needed ? What does it mean not to set any value ?Intend
In HTML5, some attributes do not need to have a value, 'checked' is another attribute where this is the case. I believe that when the value is left off, it is implied that the it is the same as the name (e.g. autofocus="autofocus" and checked="checked").Gaullism
My Spring app breaks when I try to use autofocus with no value on spring:form. autofocus="autofocus" works fine, though. Thanks, @Jacob.Salubrious
@Intend The autofocus attribute, as many other, is a boolean attribute type. That's why it is used only in a declarative way, not by assigning a value to it. See more details in w3c spec: w3.org/TR/html5/infrastructure.html#boolean-attributeSubstitute
Note that this does not seem to work by itself on an input that is initially hidden, e.g. in a bootstrap pop-up modal, because the attribute is handled when the element is inserted into the DOM at which point it is still hidden and thus not focusable. See this answerRailway
T
104

You can also try jQuery based method:

$(document).ready(function() {
    $('form:first *:input[type!=hidden]:first').focus();
});
Towage answered 10/11, 2008 at 21:1 Comment(7)
It Works! I'm starting to integrate jQuery in my web application. So, I think I will stick with this approach! Many thanks, Marko!Kipper
What happens if the first form on the page is hidden in this case? Or if the first element on the form is hidden via CSS? Surely this would fail. I am being pedantic of course but that's how I roll.Redtop
In my case (using ASP.NET) I have just ONE form which is never hidden. So this works for me.Kipper
@Jame Hughes, you can write it as a function and call it when u need it, and you can make exceptions. For me this solution really helped.Bukavu
this is not working for me for some reason. shouldn't I see a cursor.Astromancy
@AdonisSMU Please, paste your HTML somewhere.Towage
This slightly simpler version should suffice: $(':input[type!=hidden]:first').focus()Harmful
B
43
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.

Banna answered 10/11, 2008 at 10:36 Comment(3)
Should be the correct answer, because question has no jquery tag.Keelykeen
@KalleH.Väravas no, it should be downvoted because it makes assumptions that are nowhere to be found in question, eg. there's at least one form. Generally, it doesn't work.Prisca
this is better b/c it works with dynamic forms seamlesslyCornett
T
21

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

$(document).ready(function() {
    $('input:visible:enabled:first').focus();
});
Throstle answered 30/4, 2010 at 13:33 Comment(1)
I was using this, noticed it runs extremely slowly on IE when have a large number >1000 of checkboxes in a table. Not sure what to do about it, might have to just give up on focusing the first input field.Aleedis
B
11

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();
Beshore answered 28/1, 2021 at 11:54 Comment(2)
Great solution - this way, the markup is still in control.Scruggs
Yes, excellent solution!!Osmious
D
7

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

Form.focusFirstElement(document.forms[0]);
Dragster answered 10/11, 2008 at 11:14 Comment(0)
O
6

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

Obliquity answered 10/11, 2008 at 10:34 Comment(0)
T
5

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();
Towage answered 10/11, 2008 at 11:1 Comment(3)
I might be wrong, but this loop doesn't have defined behaviour if forms[0] has no hidden inputs.Bassesalpes
Exactly. It is used to skip any leading hidden inputs. And it is written under assumption that there are non-hidden fields in the form. I could have done it with jQuery as well (I'll post another answer) but you didn't mention you want jQuery involved.Towage
@MarkoDumic Why waste memory if you can use a while statement?Oswaldooswalt
R
4

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>
Redtop answered 10/11, 2008 at 12:58 Comment(3)
One thing to consider here is it may match elements that are not themselves hidden but an ancestor is. That would require tracking back up the DOM and testing each ancestors visibility which I feel is serious overkill for this kind of situation.Redtop
What about <input type="text" readonly="readonly"> I think you should add such a case to your code. Normally people don't want focus on a readonly input text field. Anyway nice code and +1 thanks!Tavis
Untested but I updated it with !forms[i][j].readonly != undefinedRedtop
H
4

I'm using this:

$("form:first *:input,select,textarea").filter(":not([readonly='readonly']):not([disabled='disabled']):not([type='hidden'])").first().focus();
Hedy answered 21/8, 2013 at 3:16 Comment(0)
C
4

without jquery, e.g. with regular javascript:

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

works on Safari but not Chrome 75 (april 2019)

Cogent answered 19/4, 2019 at 12:28 Comment(0)
I
3

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();
Ingraham answered 25/1, 2013 at 4:43 Comment(0)
L
2

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();
Lacking answered 23/10, 2012 at 2:25 Comment(0)
B
1

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">
Breakfast answered 20/10, 2014 at 6:28 Comment(0)
G
0

With AngularJS :

angular.element('#Element')[0].focus();
Groundspeed answered 8/5, 2014 at 12:2 Comment(0)
D
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(); }
});
Disfigure answered 2/6, 2014 at 11:30 Comment(0)
S
0

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;
                }
            }
        }
    }   
}
Salzman answered 6/12, 2017 at 15:19 Comment(0)
I
0

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..

Ingle answered 18/2, 2019 at 17:25 Comment(0)
J
0

This was the jQuery code that worked best for me.

$("form").find('input, textarea').first().focus();

I added textarea for the likely event that the first form input element is a textarea.

Jecon answered 25/10, 2023 at 14:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.