Josh
Josh

Reputation: 3611

How to set focus on textbox and/or control after clicking an asp label?

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>

Upvotes: 2

Views: 6591

Answers (5)

Arfan Shaikh
Arfan Shaikh

Reputation: 11

This is the Best way to write and avoid javascript

<p>

<asp:Label ID="lblName" runat="server" AssociatedControlID="txtFirstName" Text="First Name: " />

<asp:TextBox ID="txtFirstName" runat="server" />

</p>

Upvotes: 1

Aristos
Aristos

Reputation: 66641

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.

Upvotes: 3

Matt Sherman
Matt Sherman

Reputation: 8358

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.

Upvotes: 0

Nate Dudek
Nate Dudek

Reputation: 1265

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"></script>

Upvotes: 0

Kangkan
Kangkan

Reputation: 15571

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.

Upvotes: 0

Related Questions