jQuery: Focus on First Form Element

All in all, jQuery is pretty cool. I just stated working with it for a personal project and have found it simple and fairly intuitive to use, not to mention the plethora of available plug-ins.

I wanted to focus on the first input element in a form using jQuery. I haven’t tested this extensively, but I came up with the following:

    $(document).ready(function() {
       // focus on the first text input field in the first field on the page
        $("input[type='text']:first", document.forms[0]).focus();

We are simply using a selector to pick the first input element of type “text” in the first form on the page (that’s the “document.forms[0]” stuff) and then focus on it. Of course, this is limited only to text fields, but could be extended to other types as well. I’d be interested in hearing about alternatives.

About these ads

5 Comments on “jQuery: Focus on First Form Element”

  1. Robmcm says:

    Very handy!


  2. genius says:

    Too whiny. Try this instead.


  3. ctran says:

    Even better

  4. PP says:

    Does not work if there is a hidden div somewhere in between which has a enabled textbox.

  5. If you want to have more control about this there’s another alternative with this plugin:


    -After you install it you will have automatically focused your first inputs without adding a single line of code to your app.

    -Another nice thing is that you can disable this behaviour by just passing “:autofocus => false” to your forms_for.

    -Another advantage is that there’s no dependency with Prototype or JQuery.

    Oh sorry, there are some dependencies, you’ll need Rails and a browser that can understand javascript ;)


Get every new post delivered to your Inbox.

Join 25 other followers