GreatWebGuy Self-proclaimed greatness is a hard thing to prove.

16Jun/0822

Input focus with jQuery

Form input focus always seems a pain to me, I don't like all of the generated inline javascript that struts or other frameworks add to accomplish this and it always seems to be one issue or another. So here's a simple solution that applies focus to the last input element in the document that has a class of focus. Short and sweet, nothing fancy, requires the jQuery library of course.

The javascript, preferrably in an external javascript file

    $("input.focus:last").focus();

The html

Comments (22) Trackbacks (0)
  1. You could also use :

    $(“:input”).each(function () {
    this.focus(); });
    This way you don’t need to set the class=”focus” .It uses the selectors api.

  2. I’m not sure this accomplishes the same thing, how do you control which input box gains focus then? The idea behind setting a class of focus is, say you have a search field that’s always present in the header of the page that you want to have focus as long as nothing else has focus, but on certain pages like login, for example, you want the username field to have focus instead, in my example both would have a class of focus, but the last field with the focus class specified in the document would actually end up with the focus.

  3. Im missing something here… only one element of a page can have the focus, so why are you using “each”?

    Its easier something like this:

    $(“#fieldId”).focus(); or $(“input.focus”).focus();

    or maybe $(“:input:first”).focus();

    Bye :)

  4. You’re right there’s probably a better and more efficient way to do this rather than use each, it might even be a little lazy. The goal is to have the last field with focus specified receive focus. The each method does a couple of things for me: if there’s more than one field specified with focus, the method will loop through those elements and the last one will end up with focus; if there are no items with focus there will be no jQuery objects returned and I won’t end up with a javascript error because I asked for focus on something that didn’t exist. Note your syntax above is not correct as focus in this context is a DOM method, not a jQuery method.

  5. I dont think so, $(…).focus() is another jQuery method, to call the DOM method you need this $(…).get(0).focus().

    jQuery is smart enought to dont execute focus() if there is no matched elements, just like each(). Try it for yourself :)

    “Triggers the focus event of each matched element”: http://docs.jquery.com/Events/focus

    Thanks for reply ;)

  6. I stand corrected, I misinterpreted the doc, I’ll update the post. Thanks for the feedback.

  7. using a class selector without a tagname is far far far slower. always use “input.focus” instead of “.focus” when possible.

  8. Paul, thanks for the advice, I’ve updated the post again to reflect it. I’ve truly been schooled on this one.

  9. Thanks, I needed this for one of the sites I’m working on…

  10. There is no need to complicate things. You can do everything using selectors, following code will set focus on first visible input.

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

    • Actually there was a need to complicate it a little in order to have a level of control, with shared templates there’s a need for a hierarchy of focus, this is why I chose to give a class to the objects in the page that typically have focus and then apply focus to the last element with that class based on the document order.

    • Thanks! This is what I was looking for! :)

  11. Hi there. Guys, I have been using JQuery for the last 8 months and the more I use it the more I like it. The question I have is: Is there a bible for JQuery written down or Online which I can consult and study to become a Guru in the subject? can you direct it to me?

    I really appreciate it.

    • jQuery has great documentation for their API at http://docs.jquery.com/Main_Page, of course there are tutorials and examples throughout the Internet. When I first started out I skimmed a book called Learning jQuery by Jonathan Chaffer and Karl Swedberg, once you get a lot of the concepts down you’ll find that you’ll use the API documentation 90% of the time.

  12. Thank you a lot. I will go ahead and purchase the book I mean, I have been going off and on to the API documentation and I have managed to add few jquery features to some sites I have worked on however I feel like I gotta work more on the fundamentals and concepts. Every time I have to use JQuery I end up fishing some pieces of code written by somebody else (which is not bad per sea) but it doesn’t come easy.

    Cheers.

    • @joe,
      this is an old thread but in case anyone reads this question again.
      in my opinion the absolute best way is to become strong in jquery is to
      1. get a decent handle on javascript. learn functions & objects, maybe read D.Crockford’s “the good parts” and wrestle through it as many times as it takes.
      2. Then get Orielly (D.Flanagan) jQuery pocket reference and read it cover to cover. Small book but packed with everything you need on the core jquery.
      3. bookmark the jquery source and reference the functions you are calling.

  13. Hey guys.

    I’m trying to make a site that uses PHP in the backend, jQuery to make the UI fancy, and Ajax calls to populate some of the elements. I have a page that shows a bunch of data from a table, using Ajax to get back just a few records at a time. I have a filtering system where I use INPUT fields to let the user filter the data. My problem is that the INPUT field itself is being created by the same Ajax call. What happens is that the INPUT field loses focus no matter what I do.
    So far, if I combine .select() and .focus(), I can get the focus to the *beginning* of the text field, which doesn’t really work for a “type into” application. If I want to filter by “Jones”, I end up with “senoJ”.
    My code is:
    var savedfiltfield;

    $(‘tr.filter input’).live(‘keyup’, function() {
    savedfiltfield = $(this).attr(‘id’);
    setfilt($(this));
    });

    // in setfilt() function:
    $.get(‘listing_ajax.php’, {type : type, page : newpage, sort : sort, filt : filt, rowcnt : rowcnt},
    function(data) {
    $(‘table#maindata’).html(data);
    $(‘input.#’+savedfiltfield).focus();
    }
    );

    If I add .select() after the .focus(), it will select the text. If I put .select() before the .focus(), it will put the cursor at the beginning of the field.

    HELP!?!?

    Thanks.

  14. works nice! thanks =)

  15. I found this method to be very useful for me. I figured this would probably help me remember to set the tab index as well.

    $(document).ready(function(){
    $(“input[tabindex=0]“).focus();
    });


  16. webguy:

    I stand corrected, I misinterpreted the doc, I’ll update the post. Thanks for the feedback.


    webguy:

    jQuery has great documentation for their API at http://docs.jquery.com/Main_Page, of course there are tutorials and examples throughout the Internet. When I first started out I skimmed a book called Learning jQuery by Jonathan Chaffer and Karl Swedberg, once you get a lot of the concepts down you’ll find that you’ll use the API documentation 90% of the time.

  17. is that any buddy help to tell that how can i set focus in loop on different different id plz help…….
    (www.askinterview.com)

  18. Thanks….Nice Collection..!!


Leave a comment

(required)

No trackbacks yet.