416

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>
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
tenstar
  • 9,816
  • 9
  • 24
  • 45

13 Answers13

683

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>
mohkhan
  • 11,925
  • 2
  • 24
  • 27
  • 3
    You'd have to scan the document using other parts of the Web API (e.g. [`Document.forms`](https://developer.mozilla.org/en-US/docs/Web/API/document.forms), [`Document.getelementsByTagName`](https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByTagName) or [`Node.childNodes`](https://developer.mozilla.org/en-US/docs/Web/API/Node.childNodes)) and either rely on a known document structure or look for some element specific properties. – peterph Jun 16 '14 at 10:03
  • 54
    Or the obvious answer... give it an ID ;) – Relevant Aug 27 '14 at 22:52
  • 5
    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. – Chris Love Nov 23 '15 at 19:18
  • 22
    @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. – PandaWood May 04 '16 at 00:59
  • 1
    @PandaWood 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();` – Robert McKee Jun 01 '16 at 16:20
  • 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. – mAAdhaTTah Feb 08 '17 at 05:45
  • 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. – Chris Love Feb 14 '17 at 16:31
  • 7
    @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 – Toni Leigh Mar 21 '17 at 13:25
  • @toni ids are over specified because the code reference is too specific and not reusable. – Chris Love Mar 26 '17 at 18:02
  • 2
    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. – ConductedClever Dec 30 '18 at 08:37
  • 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. – Kamil Kiełczewski Apr 09 '19 at 08:10
  • 1
    Does not work in Firefox even in 2020: https://bugzilla.mozilla.org/show_bug.cgi?id=277178 , https://stackoverflow.com/questions/5327811/focus-set-focus-on-a-target-input-will-not-work-in-firefox – Abdull May 22 '20 at 09:17
  • 1
    setting the id attribute on an input is valid and recommended to specify it's label.
    This pattern is especially useful when using radio buttons, because users can click the associated label text.
    – nuiun Feb 16 '21 at 08:32
  • @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)! – Yann Dìnendal Dec 21 '22 at 17:17
194

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 />
Per Lundberg
  • 3,837
  • 1
  • 36
  • 46
a better oliver
  • 26,330
  • 2
  • 58
  • 66
  • 73
    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. – Mar Sep 26 '14 at 16:44
  • 1
    I'm afraid autofocus attribute is not compatible if IOS Safari (https://caniuse.com/#search=autofocus) while .focus() is just incompatible with Opera Mini (https://caniuse.com/#search=focus) – lfrodrigues May 22 '17 at 21:07
  • 5
    Note that if you are trying to focus from the console then it is not possible! – Or Choban Apr 04 '19 at 09:03
  • It also work when using innerHTML with an input that has `autofocus`. – Jens Törnell May 26 '21 at 11:53
  • 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. – StefaDesign Mar 04 '22 at 16:45
81

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.

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
41

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()

RajnishCoder
  • 3,455
  • 6
  • 20
  • 35
Richard Rebeco
  • 753
  • 11
  • 13
  • 16
    I downvoted this, because there is remotely no implication of jQuery in the base question. The OP wanted to stay purely javascript – Fallenreaper Jun 02 '15 at 19:59
  • 15
    Well, you have reason, I went wrong, but i think that it is helpful anyway. – Richard Rebeco Jun 19 '15 at 13:35
  • 6
    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. – paradite Jun 14 '16 at 06:56
  • 17
    @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? – Gellie Ann Oct 18 '17 at 02:30
  • 1
    @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. – Fallenreaper Oct 18 '17 at 16:27
  • 1
    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. – Adam R. Turner Jan 11 '19 at 15:46
  • 2
    @Fallenreaper that's just being pedantic –  Jan 06 '22 at 18:22
  • @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 it – symbiont Apr 05 '23 at 13:48
23

For plain Javascript, try the following:

window.onload = function() {
  document.getElementById("TextBoxName").focus();
};
sipp
  • 430
  • 3
  • 12
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. ;)

RajnishCoder
  • 3,455
  • 6
  • 20
  • 35
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
Mac
  • 1,432
  • 21
  • 27
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>
Balaji
  • 9,657
  • 5
  • 47
  • 47
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>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
1

this example worked for me

$(document).ready(function () {
document.getElementById('TextBox').focus();
}
CenkerK
  • 11
  • 3
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.

Dharman
  • 30,962
  • 25
  • 85
  • 135
StefaDesign
  • 929
  • 10
  • 19
0

Try This:

$('.modal').on('shown.bs.modal', function () {
        setTimeout(function() {
                $("input#yourFieldId").addClass('modal-primary-focus').focus();
            },
            500);
    });
Lidprogsky
  • 43
  • 8
0
<input type="text" class="word"> //html code

let theinput = document.querySelector(".word"); //Get the input 
 theinput.focus(); // focus on input 
   
Omar Saade
  • 320
  • 2
  • 8