Change RadioButtonList selected index using Javascript
Requirement:
Change RadioButtonList selected index on Reset button to default option. This will cover below topicalso:-
– JavaScript Get RadioButtonList Selected Value
– Javascript Change RadioButtonList selected index
– respond to asp:RadioButtonList changes
Solution:-
I have below ASPX code for RadioButtonList:
1 2 3 4 5 6 7 8 | <div> <asp:RadioButtonList ID="rblStatus" runat="server" RepeatDirection="Horizontal"> <asp:ListItem Value="Active_0">Active</asp:ListItem> <asp:ListItem Value="Inactive_1">Inactive</asp:ListItem> </asp:RadioButtonList> </div> <asp:Button ID="bttnReset" runat="server" Text="Reset" OnClientClick="javascript:resetAll("Inactive_1"); return false;"/> |
asp:RadioButtonList render as input type=”radio” HTML elements.
So to get asp:RadioButtonList client id, call getElementsByTagName(“input”) which will return an array of radio buttons.
Write a for statement to iterate the array and use as required.
See below code which render on html (you can check by view source page)
1 2 3 4 5 6 7 8 9 10 | <div> <table id="MainContent_rblStatus"> <tr> <td><input id="MainContent_rblStatus_0" type="radio" name="ctl00$MainContent$rblStatus" value="Active_" /> <label for="MainContent_rblStatus_0">Active</label></td> <td><input id="MainContent_rblStatus_1" type="radio" name="ctl00$MainContent$rblStatus" value="Inactive_1" /> <label for="MainContent_rblStatus_1">Inactive</label></td> </tr> </table> </div> |
Now I write below JavaScript by which when I click on reset button it will change RadioButtonList value to defualt one.
1 2 3 4 5 6 7 8 9 10 11 | function resetAll(rbDefaultValue) { var RBID = '<%=rblStatus.ClientID %>'; var RB1 = document.getElementById(RBID); var radio = RB1.getElementsByTagName("input"); for (var i = 0; i < radio.length; i++) { if (radio[i].value == rbDefaultValue) { radio[i].checked = true; } } } |
Thanks!
Avinash
May 17, 2012
В·
Infoyen В·
2 Comments
Tags: asp, dotnet, javascript В· Posted in: ASP .NET, JavaScript
2 Responses
It’s a simple code, but not present anywhere…
It is for make the radio button to be selected.
Leave a Reply