jQuery and ASP.NET

May 28, 2010

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

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

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions