Search code examples
c#jqueryasp.netradio-buttonradiobuttonlist

Adding attributes to radio buttons of radiobuttonlist


I need to add some javascript function to the multiple radio buttons rendered using radio button list. Instead they are added to span created dynamically. See the codes.

RAW html/aspx

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">
        function DisplayAlert() {
            alert('hahahahahahahahhahah');

        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:RadioButtonList runat="server" ID="rblAmit" AutoPostBack="false" 
     DataTextField="Name" DataValueField="Id">  </asp:RadioButtonList>
        </div>
    </form>
</body>

Rendered HTML

<div>
    <table id="rblAmit">
    <tr>
        <td><span onchange="javascript:DisplayAlert();"><input id="rblAmit_0" type="radio" name="rblAmit" value="A1" /><label for="rblAmit_0">Amit</label></span></td>
    </tr><tr>
        <td><span onchange="javascript:DisplayAlert();"><input id="rblAmit_1" type="radio" name="rblAmit" value="A2" /><label for="rblAmit_1">Ranjan</label></span></td>
    </tr><tr>
        <td><span onchange="javascript:DisplayAlert();"><input id="rblAmit_2" type="radio" name="rblAmit" value="A3" checked="checked" /><label for="rblAmit_2">Senior</label></span></td>
    </tr><tr>
        <td><span onchange="javascript:DisplayAlert();"><input id="rblAmit_3" type="radio" name="rblAmit" value="A4" /><label for="rblAmit_3">Software</label></span></td>
    </tr><tr>
        <td><span onchange="javascript:DisplayAlert();"><input id="rblAmit_4" type="radio" name="rblAmit" value="A5" /><label for="rblAmit_4">Engineer</label></span></td>
    </tr>
</table>

    </div>

CS-Codebehind

private void FireEventOnLoad()
{

    foreach (ListItem item in rblAmit.Items)
    {
        item.Attributes.Add("onchange", "javascript:DisplayAlert();");
    }

    if (rblAmit.Items.FindByText("Senior") != null)
    {
        rblAmit.Items.FindByText("Senior").Selected = true;
    }
}

OR

Any way so that I can enumerate RadioButtons from the RadioButtonList. Current I am getting a Key Value pair list.


Solution

  • OnChange events are associated with elements whose value attribute can change. You can use the onclick event instead and this will delegate to the input element under the span.

    private void FireEventOnLoad()
    {
    
        foreach (ListItem item in rblAmit.Items)
        {
            item.Attributes.Add("onclick", "javascript:DisplayAlert();");
        }
    
        if (rblAmit.Items.FindByText("Senior") != null)
        {
            rblAmit.Items.FindByText("Senior").Selected = true;
        }
    }