Get Selected Values From Radio Button using jQuery

Let’s say you have following radio options for the user, and you need to retrieve the value from selected radio button using jQuery.

1
2
3
4
5
<div>Choose option:</div>
<input type="radio" name="user_options" value="css" /> CSS
<input type="radio" name="user_options" value="jquery" /> jQuery
<input type="radio" name="user_options" value="html" /> HTML
<input type="radio" name="user_options" value="xml" /> XML

This jQuery line below retrieves the value of selected radio box.

1
var checked_site_radio = $('input:radio[name=user_site]:checked').val();

But when radio isn’t checked, “undefined” error returns, to deal with undefined value do this :

1
2
3
4
5
var checked_site_radio = $('input:radio[name=user_site]:checked').val();
if(checked_option_radio!=undefined)
{
    //do stuff
}

The complete example :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<!DOCTYPE html>
<html>
<head>
<title>Radio Button Selection</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("#radio_submit").click(function (e) {
        var checked_option_radio = $('input:radio[name=user_options]:checked').val();
        var checked_site_radio = $('input:radio[name=user_site]:checked').val();
       
        if(checked_option_radio===undefined || checked_site_radio===undefined)
            {
                alert('Please select both options!');
            }else{
                alert('Your option - "' +checked_option_radio + '", and site - "'+ checked_site_radio +'"');
            }
    });
});

</script>
</head>
<body>
<form id="myform">
<div>Choose option:</div>
<input type="radio" name="user_options" value="css" /> CSS
<input type="radio" name="user_options" value="jquery" /> jQuery
<input type="radio" name="user_options" value="html" /> HTML
<input type="radio" name="user_options" value="xml" /> XML

<div>Another option:</div>
<input type="radio" name="user_site" value="Google" /> Google
<input type="radio" name="user_site" value="Yahoo" /> Yahoo
<input type="radio" name="user_site" value="Facebook" /> Facebook
<input type="radio" name="user_site" value="Twitter" /> Twitter

<div><button id="radio_submit" type="button">Show Selected Radio</button></div>
</form>
</body>
</html>

Demo

Choose option:

CSS
jQuery
HTML
XML

Another option:

Google
Yahoo
Facebook
Twitter