Get Selected Value of Radio Button using a Single line of jQuery code

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).

image

See a Live Demo




About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

2 comments:

Mohit said...

how to achive the same functionality in MVC 3 for RadioButtonFor i.e RadioButtonList???

Unknown said...

Thank you very much. Nice and simple :)