443

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>
2
  • 31
    As simple as document.getElementById('your_text_box_id').focus();. Commented Jul 6, 2013 at 7:20
  • 4
    Not an answer, but people should also know that just adding autofocus on the html input tag is often enough. Commented Jul 22, 2023 at 9:13

13 Answers 13

720

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>
Sign up to request clarification or add additional context in comments.

15 Comments

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.
Or the obvious answer... give it an ID ;)
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.
@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.
@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 describe
|
214

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

5 Comments

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.
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)
Note that if you are trying to focus from the console then it is not possible!
It also work when using innerHTML with an input that has autofocus.
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.
91

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.

3 Comments

This can be a real headache on a smaller screen if the field is off screen :-)
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.
This is the proper answer for a more complex page.
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()

8 Comments

I downvoted this, because there is remotely no implication of jQuery in the base question. The OP wanted to stay purely javascript
Well, you have reason, I went wrong, but i think that it is helpful anyway.
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.
@Fallenreaper 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?
@Fallenreaper that's just being pedantic
|
23

For plain Javascript, try the following:

window.onload = function() {
  document.getElementById("TextBoxName").focus();
};

Comments

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

Comments

3

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>

Comments

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

2 Comments

AFAIK Form doesn't have "name" attribute
Forms have had "names" for a long time now, and in HTML5, they still do. See w3.org/TR/html5/forms.html#the-form-element
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>

Comments

1

this example worked for me

$(document).ready(function () {
document.getElementById('TextBox').focus();
}

Comments

1
<input type="text" class="word"> //html code

let theinput = document.querySelector(".word"); //Get the input 
 theinput.focus(); // focus on input 
   

Comments

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

 //focusId is ID of element you need focus on
   var el = document.getElementById(focusId); 
   el.focus();

solved the issue so DOM completes blur without adding delay.

Comments

0

Try This:

$('.modal').on('shown.bs.modal', function () {
  setTimeout(function() {
    $("input#yourFieldId").addClass('modal-primary-focus').focus();
   }, 500);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.