How to change onclick attribute of a HTML Label in codebehind

4.8k Views Asked by At

ok, i have this:

<div class="radio-toolbar">  
    <input type="checkbox" id="check1" name="checks" value="1">
    <label for="check1">1</label>

    <input type="checkbox" id="check2" name="checks" value="2">
    <label for="check2">2</label>

    <input type="checkbox" id="check3" name="checks" value="3">
    <label for="check3">3</label>
</div>

and i'm looking for a way to set the "onclick" attribute of those labels with ASP.NET VB Codebehind, making the labels looks like:

<div class="radio-toolbar">  
    <input type="checkbox" id="check1" name="checks" value="1">
    <label for="check1" onclick="some javascript">1</label>

    <input type="checkbox" id="check2" name="checks" value="2">
    <label for="check2" onclick="some javascript">2</label>

    <input type="checkbox" id="check3" name="checks" value="3">
    <label for="check3" onclick="some javascript">3</label>
</div>

so, is that possible?

3

There are 3 best solutions below

0
On

Use a asp:Label.

<asp:Label ID="lblChk1" runat="server" AssociatedControlID="check1" Text="1">
</asp:Label>

Then in your code behind:

lblChk1.Attributes.Add("onclick","some javascript");

Edit: You could simply use asp:CheckBox and use its Text Property. Clicking the text would then fire the onclick event of your CheckBox.

1
On

Set the ID attribute and add runat=server for your labels. Then you can access the labels from your code-behind:

<div class="radio-toolbar">  
    <input type="checkbox" id="check1" name="checks" value="1">
    <label ID="label1" runat="server" for="check1">1</label>

    <input type="checkbox" id="check2" name="checks" value="2">
    <label ID="label2" runat="server" for="check2">2</label>

    <input type="checkbox" id="check3" name="checks" value="3">
    <label ID="label2" runat="server" for="check3">3</label>
</div>
0
On

Instead of a html label i would use the ASP.NET Label control with AssociatedControlID attribute which is rendered as label for.

<asp:Label ID="Label1" 
   AssociatedControlID="check1" 
   onclick="somejavascript" 
   runat="server" 
   Text="1"></asp:Label>  

You can also add the javascript from codebehind:

Label1.Attributes.Add("onclick","somejavascript");

From MSDN:

... When the AssociatedControlID property is set, the Label control renders as an HTML label element, with the for attribute set to the ID property of the associated control. You can set other attributes of the label element using the Label properties. For example, you can use the Text and AccessKey properties to provide the caption and hot key for an associated control.

`