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.

6 comments:

  1. good one :) - vinoth

    ReplyDelete
  2. Tks! Help me a lot.

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

    ReplyDelete
  4. Mathieu: Just use the following:

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

    ReplyDelete
  5. 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.

    ReplyDelete