JavaScript set focus to HTML form element

JavaScript set focus to HTML form element

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:

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


Solution 1:

Do this.

If your element is something like this..

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

Your script would be

function setFocusToTextBox(){

Solution 2:

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:

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

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

Check if it helps.

Solution 4:

If your code is:

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

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

function setFocusToTextBox(){

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

Solution 5:

For plain Javascript, try the following:

window.onload = function() {

Solution 6:

I used to just use this:

    <script type="text/javascript">
      function focusFieldOne() {

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

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