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

Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

3 comments:

ranadheer reddy said...

HI. Nice post. This post also explains getting selected radio button value using JQuery: http://coding-issues.blogspot.in/2013/11/get-selected-radio-button-value-jquery.html

Mohit said...

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

red der said...

Thank you very much. Nice and simple :)