Set Focus to the First TextBox on a Page using jQuery

While browsing the asp.net forums, I came across a question where a user wanted to set focus to the first textbox in a Page. The condition here was the TextBox had to be enabled. Here’s how to do so:

HTML Page

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Select the First Enabled TextBox on the Form</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("input[type='text']:enabled:first").focus();
});
</script>
</
head>
<
body>
<
input id="Text1" type="text" disabled="disabled"/><br />
<
input id="Text2" type="text" disabled="disabled"/><br />
<
input id="Text3" type="text" /><br />
<
input id="Text4" type="text" /><br />
<
input id="Text5" type="text" />
</
body>
</
html>

ASP.NET Page

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Select the First TextBox on the Form</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("form :input[type='text']:enabled:first").focus();
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:TextBox ID="tb1" runat="server" Enabled="false"/><br />
<
asp:TextBox ID="tb2" runat="server" Enabled="false"/><br />
<
asp:TextBox ID="tb3" runat="server"></asp:TextBox><br />
<
asp:TextBox ID="tb4" runat="server"></asp:TextBox><br />
<
asp:Button ID="Button1" runat="server" Text="Button" /><br />
</
div>
</
form>
</
body>
</
html>

OUTPUT

image

As you can observe, the focus is set to the third textbox since the first two are disabled.



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

6 comments:

Mike Knowles said...

Good one, thanks.

Anonymous said...

good one :) - vinoth

Anonymous said...

Tks! Help me a lot.

Mathieu said...

Would it be possible to set focus to the second or third or last text box which is active?

Suprotim Agarwal said...

Mathieu: Just use the following:

second - enabled:eq(1)
third - enabled:eq(2)
last - enabled:last

Mathieu said...

Thank you for the feedback. Also, it is possible to set it for the first checkbox or text box. Since some of our pages have a mix of checkbox and text boxes, and depending on the page it could be one or the other on top.