17 January 2008 ~ 7 Comments

Set focus on first field with jQuery

f you are using Prototype see this post.

Setting focus on the first text field with jQuery is as simple as

  $("input:text:first").focus();
  $("input:text:visible:first").focus();

Find more at http://docs.jquery.com/Selectors

Update: If you are on Rails use auto_focusable_forms, dependency free plugin that will focus first input for you.

7 Responses to “Set focus on first field with jQuery”

  1. Webmster Mexico 23 April 2008 at 6:46 am Permalink

    Nice code, jquery is cool. Thanks for the example.

  2. Daniel Cadenas 15 October 2008 at 4:42 pm Permalink

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

    http://github.com/dcadenas/auto_focusable_forms/tree/master

    -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 ;)

  3. verrier 29 May 2009 at 11:33 am Permalink

    one extra bit add a visible
    $(“input:text:first:visible”).focus();

  4. Jancis 4 September 2009 at 10:41 am Permalink

    how about $(”input:text:visible:first”).focus();?
    I am not sure how filter work, but if they are taken from left to right, then visible should be filtered out first.

  5. Kevin Peno 24 December 2009 at 12:16 am Permalink

    “how about $(”input:text:visible:first”).focus();?”

    Actually, that should be: $(“:input:text:visible:first”).focus();

    This will grab focus to the first form field, regardles sof type (select, input, textarea).

  6. Kevin Peno 24 December 2009 at 12:19 am Permalink

    Correction, I meant to remove the :text part of my query. Should be:

    $(“:input:visible:first”).focus();


Leave a Reply