html - how - input focus javascript




Is there any pure-html attribute to specify which element should be focused on load (3)

And if there isn't, is there a good reason why?


Is TABINDEX=0 not working for you?

EDIT:

Sorry - hurried my answer. TABINDEX=0 will work only if the user hits the "TAB" key. Sorry about that. The following will set focus properly on load. Tested in latest IE, FF, Opera, Safari, & Chrome.

<form>
     <input id="first" tabindex="1" /><br/>
     <input id="second" tabindex="2" />
   <script>
 document.getElementById("first").focus();
   </script>
</form>

No.

And probably no good reason; everything seems obvious in hindsight.


This is coming as a part of HTML 5, so the lack of it in prior version is probably more of an oversight or a case of there being other options lowering the priority.

If you're curious, the syntax will be something like:

<input type="text" name="abc" value="" autofocus>

By the standard, it must only be declared once on a page.

In the meanwhile, with the state of the nation, you can only really do it with script in the onload event. The easiest way, is to assign the default element on the page a consistent id (call it 'autofocus') and then always set it like:

var a_focus = document.getElementById('autofocus');
if(a_focus) a_focus.focus();

Hope that helps.







focus