August 25, 2010

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

'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP 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 has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

0 Responses to "Get Selected Value of Radio Button using a Single line of jQuery code"
 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions