Getting selected value from asp:RadioButtonList in JavaScript

Raja
Posted by in JavaScript category on for Intermediate level | Views : 117380 red flag
Rating: 2.25 out of 5  
 4 vote(s)

While writing UI code, we must have came across scenaio where we need to get the asp:RadioButtonList value into JavaScript and validate some other field.
HTML Code

In following code I am getting asp:RadioButtonList and populating 3 ListItems. Then I have a button and I am calling a JavaScript function when it is clicked.

<table>

<tr>
<td>
<asp:RadioButtonList ID="radiobuttonlist1" runat="Server" RepeatLayout="flow" RepeatDirection="horizontal">
<asp:ListItem Text="Radio 1" Value="1" Selected="True"></asp:ListItem>
<asp:ListItem Text="Radio 2" Value="2"></asp:ListItem>
<asp:ListItem Text="Radio 3" Value="3"></asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
<input type="button" value="Submit" onclick="GetRadioButtonValue('<%= radiobuttonlist1.ClientID %>')" />
</td>
</tr>
</table>

JavaScript Code

In following code, I am getting the radio button element looping through its length. Checking each radiobutton for its checked value by accessing thorugh its index. As I am using RadioButtonList and I have 3 ListItem so I will collection of RadioButtons that lets me get each one of them by its index. If the radio[j].checked is true and I am giving value into an alert box.


<script language="javascript" type="text/javascript">

// Get radio button list value
function GetRadioButtonValue(id)
{
var radio = document.getElementsByName(id);
for (var j = 0; j < radio.length; j++)
{
if (radio[j].checked)
alert(radio[j].value);
}
}
</script>



I hope this small article help someone in need :) Happy Coding !!
Page copy protected against web site content infringement by Copyscape

About the Author

Raja
Full Name: Raja Dutta
Member Level:
Member Status: Member
Member Since: 6/2/2008 12:47:48 AM
Country: United States
Regards, Raja, USA
http://www.dotnetfunda.com

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)