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.






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.

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.