In this post, we will see how to display the text and value of the selected ASP.NET Radio Button.
A RadioButtonList control is declared in your WebForm like this:
and gets rendered in the browser as
Here’s the jQuery code to fetch the selected radiobutton text and value
<head runat="server">
<title>Text and Value of the selected RadioButton</title>
<script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
<script type="text/javascript">
$(function () {
var $radBtn = $("table.tbl input:radio");
$radBtn.click(function () {
var $radChecked = $(':radio:checked');
$("#para").text('')
.append("<b>Index: </b>" +
$radChecked.val() + "<br/>")
.append("<b>Value: </b>" +
$radChecked.next().text());
});
});
</script>
</head>
In the code shown above, we first retrieve the radio buttons using
var $radBtn = $("table.tbl input:radio");
An ASP.NET RadioButtonList gets rendered as a table. When the user clicks on any of the radio buttons, we are storing the radiobutton which was checked in the $radChecked variable. This is done to improve selector performance as shown below:
var $radChecked = $(':radio:checked');
We then use $radChecked.val() to retrieve the checked radiobutton ‘value’ and $radChecked.next().text() to retrieve the ‘text’.
Observe how we are accessing the value of a radiobutton using $radChecked.next().text(). This is because a RadioButton gets rendered like this:
<td>
<input id="rbl_0" type="radio" name="rbl" value="0" />
<label for="rbl_0">dotnetcurry.com</label>
</td>
To access the value, which is inside the label, we use next() which finds the very next sibling of each Radiobutton, which in our case, is the label control. The value and text is displayed on the page using a paragraph. The output looks similar to the one shown below:
See a Live Demo
There are plenty of similar recipes that I have covered in my EBook 51 Recipes using jQuery with ASP.NET Controls.
Tweet
No comments:
Post a Comment