In this post, we will see how to retrieve the selected value of a RadioButton using a single line of jQuery code. This is yet another example to prove that the jQuery library is indeed “Write Less, Do More”
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Selected Radio Button (from DevCurry.com)</title>
<script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<script type="text/javascript">$(function () {$('#btnRadio').click(function () {var checkedradio = $('[name="gr"]:radio:checked').val();$("#sel").html("Selected Value: " + checkedradio);});
});
</script>
</head>
<body>
<div>
<input type="radio" name="gr" value="Milk" /> Milk <br />
<input type="radio" name="gr" value="Butter"
checked="checked" /> Butter <br />
<input type="radio" name="gr" value="Cheese" /> Ch <br />
<hr />
<p id="sel"></p><br />
<input id="btnRadio" type="button" value="Get Selected Value" />
</div>
</body>
</html>
As you can see, the crux of the example lies in a single line of jQuery code
var checkedradio = $('[name="gr"]:radio:checked').val();
We first identify all elements with the name attribute ‘gr’ and then use :checked to filter these elements to only the one, which is in a checked state. We then use .val() to retrieve the value of the checked radio button. The final step is to display the selected value in the paragraph(sel).
See a Live DemoTweet
2 comments:
how to achive the same functionality in MVC 3 for RadioButtonFor i.e RadioButtonList???
Thank you very much. Nice and simple :)
Post a Comment