Using jQuery to Set Focus on the first TextBox Kept inside a Panel/Div

In this post, we will use a small example to demonstrate how easy it is to use jQuery to select page elements and work on them.

When a page with a form loads, you often need to set focus on a page element kept inside the form. Here’s an example of how to set focus on the first TextBox kept inside a parent container, div.

<html xmlns="">
title>jQuery to Set Focus on a TextBox Kept inside a Panel/Div</title>
style type="text/css">
script src=""
script type="text/javascript">
$(function() {
$("#divOne :input[type='text']:first").focus();
div id="divOne">
TextBox1 <input id="textOne" type="text" /> <br />
TextBox2 <input id="textTwo" type="text" /> <br />
TextBox3 <input id="textThree" type="text" /> <br />

The :input selector selects all input, textarea, select and button elements. The :first selector selects the first textbox. As you can see, we are using

$("#divOne :input[type='text']:first").focus()

to set focus on the first textbox element inside the element with ID divOne. The [type=’text’] tells the selector that we are only interested in TextBoxes.

If you run the page, the first TextBox element gets focused as expected:


Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

No comments: