Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add attribute to RadioButtonList item inside the input tag asp.net

I have an asp.net RadioButtonList that is databound. The rendered list items are apparently rendered as an input of type radio, a label, and a span.

When I iterate through each ListItem and add an onclick attribute, it adds the onclick attribute to the input tag, as desired. But when I add a custom attribute, it adds it to the surrounding span. How can I get it to add it to the input tag WITHOUT changing the rendering of the RadioButtonList via a custom ControlAdapter? I'm using web site (not a project) and .net 2.0. Thanks in advance!

ASP.NET

For Each li As ListItem In Me.rbl.Items
   li.Attributes.Add("onclick", "myFunction();")
   li.Attributes.Add("myAttribute", "1")
Next

HTML

<table id="ctl00_ContentPlaceHolder1_rbl" border="0">
    <tr>
        <td><span myAttribute="1"><input id="ctl00_ContentPlaceHolder1_rbl_0" type="radio"
          name="ctl00$ContentPlaceHolder1$rbl" value="Choice1" onclick="myFunction();" />
         <label for="ctl00_ContentPlaceHolder1_rbl_0">Choice1</label></span></td>
    </tr>
</table>
like image 738
user1422348 Avatar asked Oct 21 '22 04:10

user1422348


1 Answers

You can try something like this:

Dim i As Integer = 0

For Each li As ListItem In Me.rbl.Items
   li.Attributes.Add("onclick", "myFunction();")
   ClientScript.RegisterExpandoAttribute(rbl.ClientID & "_" & i.ToString, "myAttribute", "1")
   i += 1
Next

The attributes won't be visible in HTML because added above line will generate a client script, something like

var ctl00_ContentPlaceHolder1_rbl_0 = document.all ? document.all["ctl00_ContentPlaceHolder1_rbl_0"] : document.getElementById("ctl00_ContentPlaceHolder1_rbl_0");
ctl00_ContentPlaceHolder1_rbl_0.myAttribute = "1";
var ctl00_ContentPlaceHolder1_rbl_1 = document.all ? document.all["ctl00_ContentPlaceHolder1_rbl_1"] : document.getElementById("ctl00_ContentPlaceHolder1_rbl_1");
ctl00_ContentPlaceHolder1_rbl_1.myAttribute = "1";

But the attribute will be assigned and accessible in client-side code.

like image 74
Yuriy Galanter Avatar answered Oct 23 '22 00:10

Yuriy Galanter