Computing: Website and Database Programming

Setting the input focus onto a given form field.


The screenshot below shows the main page of my AnimalDB web application. Without including some special code, the user would have to select the input filed to enter the animal name manually (by clicking with the mouse into the field) each time they want to search for an animal in the database. It would be more than conveniant if this was done automatically, each time that the page is displayed. This is possible and very easy to do using Javascript.

AnimalDB main page with search field to be focussed at page load

The simplest way to execute a Javascript script each time that a web page is loaded, is to include the script into the body part of the HTML document. Inserting a script into a HTML page may be done by placing the Javascript code between the tags <script> and </script>. The focussing action may be done using the Javascript function focus(), as a method of the edit field object.

Here the HTML code defining the animal-search edit field:

    <td width="20%" align="center" class="bold" style="padding-top:20px;"><input type="text" name="animal" id="animal" value="*"/>  
    <input type="submit" name="submit" id="submit" value="Suchen"/></td>

The edit field has been set an id called "animal" and thus may be referenced by a Javascript function using document.getElementById(). This returns the edit field object and all we have to do with this object is to apply the focus method. Here the code of the search field focussing script (just insert it into the HTML after the closing tag of the form):

    <!-- Set input focus on quick-search text field -->
    <script>
        document.getElementById('animal').focus();
    </script>


If you find this text helpful, please, support me and this website by signing my guestbook.