How can I set focus on an element in an HTML form using JavaScript?
Asked Answered
P

13

429

I have a web form with a text box in it. How do I go about setting focus to the text box by default?

Something like this:

<body onload='setFocusToTextBox()'>

so can anybody help me with it? I don't know how to set focus to the text box with JavaScript.

<script>
  function setFocusToTextBox(){
    //What to do here
  }
</script>
Properly answered 6/7, 2013 at 7:19 Comment(2)
As simple as document.getElementById('your_text_box_id').focus();.Kulsrud
Not an answer, but people should also know that just adding autofocus on the html input tag is often enough.Amorita
K
700

Do this.

If your element is something like this..

<input type="text" id="mytext"/>

Your script would be

<script>
function setFocusToTextBox(){
    document.getElementById("mytext").focus();
}
</script>
Kadi answered 6/7, 2013 at 7:21 Comment(15)
You'd have to scan the document using other parts of the Web API (e.g. Document.forms, Document.getelementsByTagName or Node.childNodes) and either rely on a known document structure or look for some element specific properties.Baillie
Or the obvious answer... give it an ID ;)Pellerin
I would advise against using an ID because it is over specified. Instead use the name or even a class. In that case you would use document.querySelector("[name='myText']") or document.querySelector(".myText") to get a reference to the input element.Verlie
@ChrisLove Interesting advice. Why is having an id being "over specified" and what, exactly, is the problem with it? It is simpler, more precise and the code to locate it, will be slightly faster, with an ID. It sounds like the most obvious and sensible thing to do, to me - if it's possible.Sniggle
@Sniggle He is probably referring to the many editor helpers that whine about CSS if you use an id with additional selectors with a message that it is overspecified because it thinks that an id should be the the only selector required as there can only be one id, completely ignorant that HTML isn't static and the other selector may change, making the styling rule a dynamic conditional. I've only heard it from beginners in CSS. However, in this case, an id seems fair, but I would typically use another method like $('form input:first').focus();Lacerta
One of the other quirks of choosing an id is that in JavaScript, an element with an id becomes a property of the global window object. So you can actually grab the ID'd element with window.mytext, believe it or not. Another reason to avoid using ids if you can help it.Philanthropy
Sorry for the late reply. When you overspecify a CSS selector you make the code less reusable. Plus you can only have a single element in the page with that ID. What really causes the issues is CSS rules defined with an id selector. From a code maintainability it makes it more fragile because the different code you have written now becomes very tied to that ID rather than a more flexible class selector. Think about how you don't reference web sites by their IP address, but rather their domain name.Verlie
@ChrisLove this isn't over-specifying a CSS selector, it's setting a HTML ID attribute - specificity is a problem in the way CSS processing parses DOM selectors, not a problem with how ID and class attributes work in HTML. It's not advisable to use the same DOM selectors to attach CSS to as it is to attach JS to, meaning you can maintain the differentiation you describeDrucilladrucy
@toni ids are over specified because the code reference is too specific and not reusable.Verlie
Note that testing in firefox developer tools, may not seem to work due to developer tool may keep the focus on itself. That does not mean, element.focus() not working on firefox.Dongdonga
When you made components (for e.g. menu and table) and if some two elements of them has same ID and both components will be included to the same html document - then you get INVALID html. So it is not good to use ID when you create reusable components.Nolte
Does not work in Firefox even in 2020: bugzilla.mozilla.org/show_bug.cgi?id=277178 , #5328311Afterward
setting the id attribute on an input is valid and recommended to specify it's label. <form><label for="user_input">User Input</label><input type="text" name="user_input" id="user_input"></form> This pattern is especially useful when using radio buttons, because users can click the associated label text.Willawillabella
@Abdull: Fixed in firefox! No need to add any javascript for it to work now (autofocus the input field only if it matches the current anchor)!Magna
in my experience, focus() alone doesn't always work, so I also throw in a select() in there as well.Mechanical
F
201

For what it's worth, you can use the autofocus attribute on HTML5 compatible browsers. Works even on IE as of version 10.

<input name="myinput" value="whatever" autofocus />
Felten answered 6/7, 2013 at 7:30 Comment(5)
Keep in mind, this only works for setting the focus when the page first loads; it can't be used to set the focus later in response to input.Burck
I'm afraid autofocus attribute is not compatible if IOS Safari (caniuse.com/#search=autofocus) while .focus() is just incompatible with Opera Mini (caniuse.com/#search=focus)Understand
Note that if you are trying to focus from the console then it is not possible!Horotelic
It also work when using innerHTML with an input that has autofocus.Inclined
autofocus attribute does work only on initial DOM page load. DOES NOT work on DOM changes (example : when you have component that will refresh DOM and apply new HTML autofocus will not work) It works with dynamic content only first time initiated. My case study was setting up focus on first result from api response so when user clicks next to load more results autofocus will not work.Rimester
C
84

Usually when we focus on a textbox, we should also scroll into view

function setFocusToTextBox(){
    var textbox = document.getElementById("yourtextbox");
    textbox.focus();
    textbox.scrollIntoView();
}

Check if it helps.

Calcification answered 6/7, 2013 at 7:25 Comment(3)
This can be a real headache on a smaller screen if the field is off screen :-)Drucilladrucy
If you have a header bar that is fixed, you might need to use textbox.scrollIntoView(false) this simply sets the element to the bottom instead of the top.Tuchun
This is the proper answer for a more complex page.Nitpicking
A
42

If your code is:

<input type="text" id="mytext"/>

And If you are using JQuery, You can use this too:

<script>
function setFocusToTextBox(){
    $("#mytext").focus();
}
</script>

Keep in mind that you must draw the input first $(document).ready()

Autonomous answered 10/3, 2015 at 18:32 Comment(8)
I downvoted this, because there is remotely no implication of jQuery in the base question. The OP wanted to stay purely javascriptLp
Well, you have reason, I went wrong, but i think that it is helpful anyway.Autonomous
I am upvoting this because in projects where jQuery is already used and you elements as jQuery selection objects, it is better to be consistent instead of using vanilla JS.Pinder
@Lp Downvotes are for egregiously sloppy, no-effort-expended post, or an answer that is clearly and perhaps dangerously incorrect, according to stackoverflow's help center. I find this nowhere near those categories. Helping is not limited to the OP, is it?Glyptograph
@GellieAnn While it is an answer, it lies outside the scope of the OPs question. There is a reason why he is using vanilla javascript, and while you can mention other frameworks and give pointers or hints to lead to one and give a reasoning why, you should still solve the answer from within the bounds of the question asked. Therefore, I stand by my downvote.Lp
In most modern browsers $("someelement") would be interpreted as document.getElementById even without jquery explicitly loaded. So this may very well work in vanilla js.Stellate
@Lp that's just being pedanticIonize
@GellieAnn "There is a reason why he is using vanilla javascript" the reason may be that he is not aware of jQuery. people that are purposely trying to avoid jQuery typically mention itInstar
I
23

For plain Javascript, try the following:

window.onload = function() {
  document.getElementById("TextBoxName").focus();
};
Injection answered 6/7, 2013 at 7:21 Comment(0)
S
3

I used to just use this:

<html>
  <head>
    <script type="text/javascript">
      function focusFieldOne() {
        document.FormName.FieldName.focus();
      }
    </script>
  </head>

  <body onLoad="focusFieldOne();">
    <form name="FormName">
      Field <input type="text" name="FieldName">
    </form>
  </body>
</html>

That said, you can just use the autofocus attribute in HTML 5.

Please note: I wanted to update this old thread showing the example asked plus the newer, easier update for those still reading this. ;)

Smythe answered 8/7, 2016 at 2:10 Comment(0)
D
2

As mentioned earlier, document.forms works too.

function setFocusToTextBox( _element ) {
  document.forms[ 'myFormName' ].elements[ _element ].focus();
}

setFocusToTextBox( 0 );
// sets focus on first element of the form
Demetra answered 22/12, 2014 at 15:22 Comment(2)
AFAIK Form doesn't have "name" attributeSeptuplet
Forms have had "names" for a long time now, and in HTML5, they still do. See w3.org/TR/html5/forms.html#the-form-elementDemetra
S
2

window.onload is to put focus initially onblur is to put focus while you click outside of the textarea,or avoid text area blur

<textarea id="focus"></textarea>
<script>
  var mytexarea=document.getElementById("focus");
  window.onload=function() {
    mytexarea.focus();
  }
</script>
Soldier answered 11/6, 2019 at 2:49 Comment(0)
E
1

If your <input> or <textarea> has attribute id=mytext then use

mytext.focus();

function setFocusToTextBox() {
    mytext.focus();
}
<body onload='setFocusToTextBox()'>
  <form>
    <input type="text" id="mytext"/>
  </form>
</body>
Enemy answered 9/4, 2019 at 6:26 Comment(0)
H
1

this example worked for me

$(document).ready(function () {
document.getElementById('TextBox').focus();
}
Hendrix answered 21/2, 2022 at 11:13 Comment(0)
R
1

Thought of sharing some edge cases for this subject. If your content is reloading (example dynamic DOM loading results from API and setting focus on first item of results) adding attribute autofocus will not be your solution, it works only on first load, second DOM change will not work but works fine in static DOM or single page load. If you have Dynamic component loading data simple .focus() will fail due to triggering focus on element not created yet by the time focus() is or blur not complete yet by DOM. For this case expected is to add delay time (setTimeout function) to give a time for focus to apply to new created or recreated element in DOM. My case was to load data from API and get focus on first result. Adding var el = document.getElementById(focusId); el.focus(); solved the issue so DOM completes blur without adding delay.

Rimester answered 4/3, 2022 at 17:9 Comment(0)
P
1
<input type="text" class="word"> //html code

let theinput = document.querySelector(".word"); //Get the input 
 theinput.focus(); // focus on input 
   
Palmitin answered 18/3, 2022 at 19:22 Comment(0)
A
0

Try This:

$('.modal').on('shown.bs.modal', function () {
  setTimeout(function() {
    $("input#yourFieldId").addClass('modal-primary-focus').focus();
   }, 500);
});
Aleron answered 11/1, 2022 at 13:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.