Focus on Input with JQuery

This is very simple and can also be done with HTML5 ‘autofocus‘ which I would recommend you use (if you can). If for some reason you need to control it with JavaScript, utalising jQuery’s .focus() event handler will get you out of trouble.

To focus on an input field with an id of search on page load, try:


$(document).ready(function() {
 $('#search').focus();
});

2 Comments

  1. Ive used this before to help support users who dont have a browser that supports the html5 autofocus, but this as autofocus should be used in circumstances that dictate its use. autofocussing on a form half way down a page can be a hinderance rather than a good feature.

    • Couldn’t agree more!

This post currently has 2 responses. What do you think?

You can use basic HTML when posting code, please turn all < characters into &lt; or > into &gt;
If the code is multi-line, use <pre><code></code></pre>

Leave a Reply

Your email address will not be published. Required fields are marked *

Current ye@r *