tags:

views:

86

answers:

4

I would like to set the focus on a textbox and/or control after clicking an asp label? Can some explain to me how to do this? Similar to doing a

<label for="txtBoxID">Blah</label>
A: 

You can do it using Javascript or jQuery.

<label for="txtBoxID" onClientClick="SetMyFocus()">Blah</label>

<javascript>
function SetMyFocus()
{
    document.getElementById("MyTextBox").focus();
}
</javascript>

If you have a specific need of doing something in the server side on the click of the label, you shall have to handle the same in code behind and then set the client side script to fire up after reloading the page. Use RegisterStartupScript for the same.

Kangkan
A: 

I'm assuming you want to do it completely on the client side to avoid a postback?

You can use jQuery to set focus. After adding a script reference to the jQuery library, you can use the following JavaScript in your page:

$(document).ready(function() {
     $("#labelId").click(function() {
          $("*[id$='txtBoxID']").focus()
     });
});

The "*[id$='txtBoxID']" selector allows you to select the ASP.NET server side ID of your textbox without any additional code. Basically, it's saying "select any DOM element whose ID ends with txtBoxId."

You can add jQuery to your page with the following CDN script reference:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"&gt;&lt;/script&gt;
Nate Dudek
A: 

A more generalized solution using jQuery:

$(document).ready(function() {
     $("label[for]").click(function() {
          var inputid = '#' + $(this).attr('for');
          $(inputid).focus();
     });
});

Should handle all labels, as long as you correctly define the for attribute.

Matt Sherman
+2  A: 

You can also do this

<label for="<%=txtName.ClientID%>">Name:</label>
<asp:TextBox runat="server" ID="txtName"></asp:TextBox>

or on dot 4.

<label for="txtName">Name: </label>
<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static"></asp:TextBox>

and avoid JavaScript.

Aristos
Hadn't thought of that. Great answer, nice and simple.
Nate Dudek