Home » AJAX

Using jQuery for setting focus on an input box

9 June 2010 One Comment

Setting a focus on an input box is a hassle with so many different browsers out there. Each browser has their own unique tag to set the focus. Rather than using the browser-specific tags for the focus, one can utilize Javascript to provide the functionality for multiple browsers.

jQuery is a great alternative to adding the focus since its simply a matter of adding a few lines of code to your page. It will work on multiple browsers, whether it be Internet Explorer, Firefox, Chrome, or Safari.

If you want the first visible element of the page to be focused:

<script type="text/javascript" >
$(function() {
$("input:text:visible:first").focus();
});
</script>

If you want a specific element to be focused, such as a search box:

For instance,<script type="text/javascript" >
$(function() {
$("input[name=\'MY_INPUT_NAME\']").focus();
});
</script>

will set the focus for your input element with the name “MY_INPUT_NAME”.

One Comment »

  • Manmohanjit said:

    Alternatively, you can use HTML5

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.

*