175

How do you automatically set the focus to a textbox when a web page loads?

Is there an HTML tag to do it or does it have to be done via Javascript?

Robert Wade
  • 4,918
  • 1
  • 16
  • 35
Mark Biek
  • 146,731
  • 54
  • 156
  • 201

14 Answers14

263

If you're using jquery:

$(function() {
  $("#Box1").focus();
});

or prototype:

Event.observe(window, 'load', function() {
  $("Box1").focus();
});

or plain javascript:

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

though keep in mind that this will replace other on load handlers, so look up addLoadEvent() in google for a safe way to append onload handlers rather than replacing.

ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193
Ben Scheirman
  • 40,531
  • 21
  • 102
  • 137
100

In HTML there's an autofocus attribute to all form fields. There's a good tutorial on it in Dive Into HTML 5. Unfortunately it's currently not supported by IE versions less than 10.

To use the HTML 5 attribute and fall back to a JS option:

<input id="my-input" autofocus="autofocus" />
<script>
  if (!("autofocus" in document.createElement("input"))) {
    document.getElementById("my-input").focus();
  }
</script>

No jQuery, onload or event handlers are required, because the JS is below the HTML element.

Edit: another advantage is that it works with JavaScript off in some browsers and you can remove the JavaScript when you don't want to support older browsers.

Edit 2: Firefox 4 now supports the autofocus attribute, just leaving IE without support.

dave1010
  • 15,135
  • 7
  • 67
  • 64
  • 3
    What's with the `autofocus="aufofocus"`? All the links you provided just say to add the attribute: `autofocus`. – Gerrat Dec 04 '14 at 15:24
  • 7
    Back in the days of XHTML and HTML4 it was common to do `attribute="value"` for boolean attributes. HTML5 came along with the "empty attribute syntax" and we dropped the redundancy. Now we can do `` – dave1010 Dec 09 '14 at 10:34
  • I like this approach... That code belongs with the input... get rid of the input and boom, the associated code is right there... We get so lost these days... Going full circle now trying to simplify... – Serge Dec 07 '18 at 03:15
17

You need to use javascript:

<BODY onLoad="document.getElementById('myButton').focus();">

@Ben notes that you should not add event handlers like this. While that is another question, he recommends that you use this function:

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

And then put a call to addLoadEvent on your page and reference a function the sets the focus to you desired textbox.

Espo
  • 41,399
  • 21
  • 132
  • 159
16

Simply write autofocus in the textfield. This is simple and it works like this:

 <input name="abc" autofocus></input>

Hope this helps.

Liam
  • 27,717
  • 28
  • 128
  • 190
Arjun
  • 163
  • 1
  • 8
  • 1
    this is good but the problem is, if you have steps with sliding style, that would not be useful esp if the input type is on the step 3 or step 4 for ex – Kobe Bryan Aug 18 '17 at 17:05
13

You can do it easily by using jquery in this way:

<script type="text/javascript">

    $(document).ready(function () {
        $("#myTextBoxId").focus();
    });

</script>

by calling this function in $(document).ready().

It means this function will execute when the DOM is ready.

For more information about the READY function, refer to : http://api.jquery.com/ready/

Undo
  • 25,519
  • 37
  • 106
  • 129
Amir Chatrbahr
  • 2,260
  • 21
  • 31
12

Using plain vanilla html and javascript

<input type='text' id='txtMyInputBox' />


<script language='javascript' type='text/javascript'>
function SetFocus()
{
    // safety check, make sure its a post 1999 browser
    if (!document.getElementById)
    {
        return;
    }

    var txtMyInputBoxElement = document.getElementById("txtMyInputBox");

    if (txtMyInputBoxElement != null)
    {
        txtMyInputBoxElement.focus();
    }
}
SetFocus();
</script>

For those out there using the .net framework and asp.net 2.0 or above, its trivial. If you are using older versions of the framework, you'd need to write some javascript similar to above.

In your OnLoad handler (generally page_load if you are using the stock page template supplied with visual studio) you can use:

C#

protected void PageLoad(object sender, EventArgs e)
{
    Page.SetFocus(txtMyInputBox);
}

VB.NET

Protected Sub PageLoad(sender as Object, e as EventArgs)

    Page.SetFocus(txtMyInputBox)

End Sub

(* Note I removed the underscore character from the function name that is generally Page_Load since in a code block it refused to render properly! I could not see in the markup documentation how to get underscores to render unescaped.)

Hope this helps.

Jon
  • 1,508
  • 15
  • 24
7

IMHO, the 'cleanest' way to select the First, visible, enabled text field on the page, is to use jQuery and do something like this:

$(document).ready(function() {
  $('input:text[value=""]:visible:enabled:first').focus();
});

Hope that helps...

Thanks...

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
revive
  • 831
  • 2
  • 15
  • 31
6
<html>  
<head>  
<script language="javascript" type="text/javascript">  
function SetFocus(InputID)  
{  
   document.getElementById(InputID).focus();  
}  
</script>  
</head>  
<body onload="SetFocus('Box2')">  
<input id="Box1" size="30" /><br/>  
<input id="Box2" size="30" />  
</body>  
</html>  
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
5

As a general advice, I would recommend not stealing the focus from the address bar. (Jeff already talked about that.)

Web page can take some time to load, which means that your focus change can occur some long time after the user typed the pae URL. Then he could have changed his mind and be back to url typing while you will be loading your page and stealing the focus to put it in your textbox.

That's the one and only reason that made me remove Google as my start page.

Of course, if you control the network (local network) or if the focus change is to solve an important usability issue, forget all I just said :)

Vincent Robert
  • 35,564
  • 14
  • 82
  • 119
  • I agree with you in some cases. However, in my specific case, I'm popping up a little div which only one input box. The user is supposed to enter something and the immediately close the div so setting the focus is handy. – Mark Biek Sep 25 '08 at 17:31
2

I had a slightly different problem. I wanted autofocus, but, wanted the placeholder text to remain, cross-browser. Some browsers would hide the placeholder text as soon as the field focused, some would keep it. I had to either get placeholders staying cross-browser, which has weird side effects, or stop using autofocus.

So I listened for the first key typed against the body tag, and redirected that key into the target input field. Then all the event handlers involved get killed off to keep things clean.

var urlInput = $('#Url');

function bodyFirstKey(ev) {
    $('body').off('keydown', bodyFirstKey);
    urlInput.off('focus', urlInputFirstFocus);

    if (ev.target == document.body) {
        urlInput.focus();
        if (!ev.ctrlKey && !ev.metaKey && !ev.altKey) {
            urlInput.val(ev.key);
            return false;
        }
    }
};
function urlInputFirstFocus() {
    $('body').off('keydown', bodyFirstKey);
    urlInput.off('focus', urlInputFirstFocus);
};

$('body').keydown(bodyFirstKey);
urlInput.focus(urlInputFirstFocus);

https://jsfiddle.net/b9chris/qLrrb93w/

Chris Moschini
  • 36,764
  • 19
  • 160
  • 190
2

It is possible to set autofocus on input elements

<input type="text" class="b_calle" id="b_calle" placeholder="Buscar por nombre de calle" autofocus="autofocus">
Merec
  • 2,751
  • 1
  • 14
  • 21
oscar castellon
  • 3,048
  • 30
  • 19
0

Adjusted my answer from Dave1010 above as JavaScript backup didn't work for me.

<input type="text" id="my-input" />

And the Javascipt backup check:

if (!(document.getElementById("my-input").hasAttribute("autofocus"))) {
    document.getElementById("my-input").focus();
}
tdahman1325
  • 210
  • 3
  • 6
-1

If you are using ASP.NET then you can use

yourControlName.Focus()

in the code on the server, which will add appropriate JavaScript into the page.

Other server-side frameworks may have an equivalent method.

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
-3

Use the below code. For me it is working

jQuery("[id$='hfSpecialty_ids']").focus()
JSK NS
  • 3,346
  • 2
  • 25
  • 42