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="http://www.w3.org/1999/xhtml">
<
head>
<
title>jQuery to Set Focus on a TextBox Kept inside a Panel/Div</title>
<
style type="text/css">
#divOne
{
height:300px;
width:150px;
top:30px;
}
</style>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("#divOne :input[type='text']:first").focus();
});
</script>
</
head>
<
body>
<
div id="divOne">
TextBox1 <input id="textOne" type="text" /> <br />
TextBox2 <input id="textTwo" type="text" /> <br />
TextBox3 <input id="textThree" type="text" /> <br />
</
div>
</
body>
</
html>

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:

image



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


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

No comments: