user2277747
user2277747

Reputation: 89

How do i set the textbox to be already in focus when my webpage loads

I want a textbox to be in focus when my webpage loads. If you go to google.com you can see the textbox is already in focus. That's what I want.

Heres my form:

<form id="searchthis" action="#" style="display:inline;" method="get">
  <input id="namanyay-search-box" name="q" size="40" x-webkit-speech/>
  <input id="namanyay-search-btn" value="Search" type="submit"/>

Upvotes: 4

Views: 459

Answers (3)

Sampson
Sampson

Reputation: 268344

Give your text input the autofocus attribute. It has fairly good browser-support, though not perfect. We can polyfill this functionality rather easily; I've taken the liberty to write up an example below. Simply place this at the bottom of your document (so that when it's ran, the elements already exist), and it will find your autofocus element (note: you should have only one, otherwise you could get inconsistent results), and draw focus upon it.

(function () {

    // Proceed only if new inputs don't have the autofocus property
    if ( document.createElement("input").autofocus === undefined ) {

        // Get a reference to all forms, and an index variable
        var forms = document.forms, fIndex = -1;

        // Begin cycling over all forms in the document
        formloop: while ( ++fIndex < forms.length ) {

            // Get a reference to all elements in form, and an index variable
            var elements = forms[ fIndex ].elements, eIndex = -1;

            // Begin cycling over all elements in collection
            while ( ++eIndex < elements.length ) {

                // Check for the autofocus attribute
                if ( elements[ eIndex ].attributes["autofocus"] ) {

                    // If found, trigger focus
                    elements[ eIndex ].focus(); 

                    // Break out of outer loop
                    break formloop;

                }

            }

        }

    }

}());

After some initial testing, this appears to provide support all the way back to Internet Explorer 6, Firefox 3, and more.

Test in your browser of choice: http://jsfiddle.net/jonathansampson/qZHxv/show

Upvotes: 3

Jan Turoň
Jan Turoň

Reputation: 32912

The HTML5 solution of Jonathan Sampson is probably the best. If you use jQuery, steo's sample should work, too. To be complete, here you go plain JS solution for all browsers and IE10+

window.addEventListener("load",function() {
  document.getElementById("namanyay-search-box").focus();
});

Upvotes: 2

steo
steo

Reputation: 4656

$(document).ready(function(){

..code.. 
$('.textbox-class-name').focus();
..code.. 
});

Or you can try it on $(window).load()

Upvotes: 0

Related Questions