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

JavascriptHtmlTextboxFocus

Javascript Problem Overview


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>

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

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

Solution 3 - Javascript

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.

Solution 4 - Javascript

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

Solution 5 - Javascript

For plain Javascript, try the following:

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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>

Solution 9 - Javascript

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>

Solution 10 - Javascript

Try This:

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

Solution 11 - Javascript

this example worked for me

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

Solution 12 - Javascript

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.

Solution 13 - Javascript

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontenstarView Question on Stackoverflow
Solution 1 - JavascriptmohkhanView Answer on Stackoverflow
Solution 2 - Javascripta better oliverView Answer on Stackoverflow
Solution 3 - JavascriptKhanh TOView Answer on Stackoverflow
Solution 4 - JavascriptRichard RebecoView Answer on Stackoverflow
Solution 5 - JavascriptsippView Answer on Stackoverflow
Solution 6 - Javascriptuser6558655View Answer on Stackoverflow
Solution 7 - JavascriptMacView Answer on Stackoverflow
Solution 8 - JavascriptßãlãjîView Answer on Stackoverflow
Solution 9 - JavascriptKamil KiełczewskiView Answer on Stackoverflow
Solution 10 - JavascriptLidprogskyView Answer on Stackoverflow
Solution 11 - JavascriptCenkerKView Answer on Stackoverflow
Solution 12 - JavascriptStefaDesignView Answer on Stackoverflow
Solution 13 - JavascriptOmarsSaadeView Answer on Stackoverflow