447

I want to get the selected value from a group of radio buttons.

Here's my HTML:

<div id="rates">
  <input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
  <input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
  <input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate
</div>

Here's my JavaScript code:

var rates = document.getElementById('rates').value;
var rate_value;
if(rates == 'Fixed Rate'){
    rate_value = document.getElementById('r1').value;

}else if(rates == 'Variable Rate'){
    rate_value = document.getElementById('r2').value;

}else if(rates == 'Multi Rate'){
    rate_value = document.getElementById('r3').value;
}

document.getElementById('results').innerHTML = rate_value;

I keep getting undefined.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ZombieBatman
  • 4,473
  • 3
  • 13
  • 4
  • 64
    You're not using jQuery here, but if you ever wanted to, you could use this: `$("input[type='radio'][name='rate']:checked").val();` – GJK Apr 05 '13 at 16:48
  • Why can't you inspect that object? Anyway you need to use `.checked` – Amol M Kulkarni Apr 05 '13 at 16:52
  • possible duplicate of [getting selected value of radio button in case of action](http://stackoverflow.com/questions/8492928/getting-selected-value-of-radio-button-in-case-of-action) – GOTO 0 Jul 23 '13 at 10:52
  • I'm not sure if that is required or not, but it is a good habit to put radio buttons in `
    ` container.
    – Kamil Jan 17 '16 at 12:27
  • 2
    Possible duplicate of [How to get the selected radio button value using js](http://stackoverflow.com/questions/3869535/how-to-get-the-selected-radio-button-value-using-js) – Damjan Pavlica Sep 26 '16 at 14:40
  • Why do you expect a `
    ` to have the checked and value properties?
    – ᴍᴇʜᴏᴠ Dec 26 '16 at 18:07

31 Answers31

736

This works in IE9 and above and all other browsers.

document.querySelector('input[name="rate"]:checked').value;
Parthik Gosar
  • 10,998
  • 3
  • 24
  • 16
  • 22
    Of course you would have to check if querySelector returns null. This is the case if no radio button is checked. – Robert Feb 03 '14 at 08:20
  • 22
    @KamranAhmed: Your jQuery solution comes with a much bigger cost. –  Dec 31 '14 at 20:21
  • 5
    ParthikGosar: IE8 doesn't support the `:checked` selector. –  Dec 31 '14 at 20:26
  • 1
    @KamranAhmed I can't imagine a situation where this performance hit would matter – Nick Manning Jan 05 '15 at 22:49
  • Lovely. And no need for a parent element. – AlikElzin-kilaka Jan 07 '15 at 15:33
  • 15
    Note that the quotation marks around `rate` are not required. – mbomb007 Apr 23 '15 at 16:38
  • 2
    @KamranAhmed until and unless you can profile the above and/or inspect the implementation behind the call, you can say no more about the performance of the above than you can say about any other oneliner that calls native code. We do not have enough information to speculate how the browser manages to locate `:checked` element(s) -- maybe it has everything "hashed and cached" and it's a `O(1)` operation. Unless you have profiled it to indicate something like query time grows with number of elements on the page, or unless you understand the browser source code behind it, you can't tell. – Armen Michaeli Jun 25 '16 at 19:03
318
var rates = document.getElementById('rates').value;

The rates element is a div, so it won't have a value. This is probably where the undefined is coming from.

The checked property will tell you whether the element is selected:

if (document.getElementById('r1').checked) {
  rate_value = document.getElementById('r1').value;
}

Or

$("input[type='radio'][name='rate']:checked").val();
Waruna Manjula
  • 3,067
  • 1
  • 34
  • 33
Joe F
  • 4,174
  • 1
  • 14
  • 13
  • 257
    In jquery it'd be `$("input[name=rate]:checked").val()` – Kamran Ahmed Nov 28 '13 at 10:31
  • 1
    I don't understand, are there two elements with the same ID? – mzalazar May 24 '14 at 15:50
  • 4
    @mzalazar No, every radio-button has its own ID but all have the same name which is what puts them into one group so if you select one the other one gets deselected. With Kamran Ahmed answer you can check which of the radio buttons in the group is selected and get only the value of the selected (checked) one. – Broco Sep 04 '14 at 18:21
  • 4
    mahdavipanah's code just above (with `[checked]`) looks for the *attribute* (i.e. initial state). You should instead use `:checked`, which looks for the *property* (i.e. current state), and which is almost always what you want. – Gras Double May 29 '18 at 12:30
  • 11
    In Javascript it'd be `document.querySelectorAll("input[name=rate]:checked")[0].value` – Vincent McNabb Jun 19 '19 at 05:38
  • 10
    In Javascript, you don't need to get _all_ of them though: `document.querySelector("input[name=rate]:checked").value`. – WhyNotHugo Jun 01 '20 at 13:45
  • $("input[type='radio'][id='rate']:checked").val(); Worked to me – colidom Mar 14 '22 at 14:48
164

You can get the value by using the checked property.

var rates = document.getElementsByName('rate');
var rate_value;
for(var i = 0; i < rates.length; i++){
    if(rates[i].checked){
        rate_value = rates[i].value;
    }
}
Joe
  • 6,401
  • 3
  • 28
  • 32
  • 17
    Given that only one radio can be checked, I'd normally expect a `break` or `return` statement inside the `if` block to stop additional passes through the loop. A minor point, but good style. – RobP May 27 '15 at 03:26
  • 2
    This is the cleanest vanilla implementation for this question. Kudos! – SeaWarrior404 Mar 21 '19 at 07:48
50

For you people living on the edge:

There is now something called a RadioNodeList and accessing its value property will return the value of the currently checked input. This will remove the necessity of first filtering out the 'checked' input as we see in many of the posted answers.

Example Form

<form id="test">
    <label><input type="radio" name="test" value="A"> A</label>
    <label><input type="radio" name="test" value="B" checked> B</label>
    <label><input type="radio" name="test" value="C"> C</label>
</form>

To retrieve the checked value, you could do something like this:

var form = document.getElementById("test");
alert(form.elements["test"].value);

The JSFiddle to prove it: http://jsfiddle.net/vjop5xtq/

Please note this was implemented in Firefox 33 (all other major browser seems to support it). Older browsers will require a polyfill for RadioNodeList for this to properly function.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Daniel
  • 4,918
  • 4
  • 33
  • 34
28

If you are using JavaScript without jQuery, you can use this command:

document.querySelector("input[type='radio'][name=rate]:checked").value;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Beweelam
  • 870
  • 9
  • 11
  • 2
    This answer is underrated but the best ! – Thanasis Feb 19 '22 at 11:30
  • 1
    Perfecto! Works well for situations where you are dynamically creating radio buttons on the fly and do not know how many radio buttons will be created. – Joseph Apr 22 '22 at 13:26
  • That works, we can more simplify, if you're sure the input element name `document.querySelector("input[name='rate']:checked")` – Code Cooker Apr 24 '22 at 02:55
  • Excellent and versatile solution when jQuery and other libraries are not in use and you don't want to add the overhead. – PolicyWatcher Dec 14 '22 at 16:35
16

Another (apparently older) option is to use the format: "document.nameOfTheForm.nameOfTheInput.value;" e.g. document.mainForm.rads.value;

document.mainForm.onclick = function(){
    var radVal = document.mainForm.rads.value;
    result.innerHTML = 'You selected: '+radVal;
}
<form id="mainForm" name="mainForm">
    <input type="radio" name="rads" value="1" />
    <input type="radio" name="rads" value="2" />
    <input type="radio" name="rads" value="3" />
    <input type="radio" name="rads" value="4" />
</form>
<span id="result"></span>

You can refer to the element by its name within a form. Your original HTML does not contain a form element though.

Fiddle here (works in Chrome and Firefox): https://jsfiddle.net/Josh_Shields/23kg3tf4/1/

JHS
  • 1,423
  • 17
  • 29
  • 1
    This is the much older legacy DOM format and really shouldn't be used anymore since it's limited to certain elements and doesn't keep pace with current standards. – j08691 Feb 27 '15 at 14:50
  • @j08691 Ah okay thanks for letting me know. This is one of the things that I learned in a University class. It's probably better not to trust anything from there and just use online references instead. – JHS Feb 27 '15 at 14:56
  • 9
    "...doesn't keep pace with current standards." is not a convincing argument. Please elaborate. If it works it works. It is also fewer lines than the accepted answer which only determines if the selected option is 'Fixed Rate'. – zeros-and-ones Mar 17 '15 at 19:45
  • The fiddle above doesn't seem to work with the Safari browser (7.1.4). The value shows as undefined, changing the radio button states does not affect that. – Stuart R. Jefferys Mar 24 '15 at 19:50
  • Yes, this also doesn't work with Edge browser (40.15063.0.0). If they deprecated this way, it seems strange, because this way is simpler and makes sense since radio buttons are grouped by their nature. Most of the other answers look just like they are checking checkboxes. – Michael K Sep 19 '17 at 19:38
16

The one worked for me is given below from api.jquery.com.

HTML

<input type="radio" name="option" value="o1">option1</input>
<input type="radio" name="option" value="o2">option2</input>

JavaScript

var selectedOption = $("input:radio[name=option]:checked").val()

The variable selectedOption will contain the value of the selected radio button (i.e) o1 or o2

Malathy
  • 337
  • 5
  • 14
14

Use document.querySelector('input[type = radio]:checked').value; to get the value of the selected checkbox. You can use other attributes to get value like name = gender, etc. Please go through the below snippet. Definitely it will helpful to you.

Solution

document.mainForm.onclick = function(){
    var gender = document.querySelector('input[name = gender]:checked').value;
    result.innerHTML = 'You Gender: '+gender;
}
<form id="mainForm" name="mainForm">
    <input type="radio" name="gender" value="Male" checked/>Male
    <input type="radio" name="gender" value="Female" />Female
    <input type="radio" name="gender" value="Others" />Others
</form>
<span id="result"></span>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pawan vedak
  • 157
  • 1
  • 5
10

HTML code

<input type="radio" name="rdoName" value="YES"/>
<input type="radio" name="rdoName" value="NO"/>

jQuery code

var value = $("input:radio[name=rdoName]:checked").val();

$("#btnSubmit").click(function() {
    var value = $("input:radio[name=rdoName]:checked").val();
    console.log(value);
    alert(value);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name="rdoName" value="YES"/> YES
<input type="radio" name="rdoName" value="NO"/> NO
<br/>
<input type="button"id="btnSubmit"value="Which one Selected"/>

You will get

value="YES" // If checked Radio Button with the value "YES"
value="NO" // If checked Radio Button with the value "NO"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
8

Shortest

[...rates.children].find(c=>c.checked).value

let v= [...rates.children].find(c=>c.checked).value

console.log(v);
<div id="rates">
  <input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
  <input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
  <input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate  
</div>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
  • By the way... `document.rates.rate.value` is lot shorter, more intuitive and works like a charm – ˈvɔlə Oct 10 '21 at 10:51
  • @WΩLLE-ˈvɔlə your code not works - I check it with question html and it thorws exception `"Uncaught TypeError: Cannot read properties of undefined"` because `reates.rate` is undefined – Kamil Kiełczewski Oct 10 '21 at 18:42
6

In Javascript we can get the values by using Id's "getElementById()" in the above code you posted has contain name not Id so you to modify like this

if (document.getElementById('r1').checked) {
  rate_value = document.getElementById('r1').value;
}

use this rate_value according to your code

Vignesh Pichamani
  • 7,950
  • 22
  • 77
  • 115
pradeep
  • 61
  • 1
  • 1
5

A year or so has passed since the question was asked, but I thought a substantial improvement of the answers was possible. I find this the easiest and most versatile script, because it checks whether a button has been checked, and if so, what its value is:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Check radio checked and its value</title>
</head>
<body>

    <form name="theFormName">
        <input type="radio" name="theRadioGroupName" value="10">
        <input type="radio" name="theRadioGroupName" value="20">
        <input type="radio" name="theRadioGroupName" value="30">
        <input type="radio" name="theRadioGroupName" value="40">
        <input type="button" value="Check" onclick="getRadioValue('theRadioGroupName')">
    </form>

    <script>
        function getRadioValue(groupName) {
            var radios = theFormName.elements[groupName];
            window.rdValue; // declares the global variable 'rdValue'
            for (var i=0; i<radios.length; i++) {
                var someRadio = radios[i];
                if (someRadio.checked) {
                    rdValue = someRadio.value;
                    break;
                }
                else rdValue = 'noRadioChecked';
            }
            if (rdValue == '10') {
                alert('10'); // or: console.log('10')
            }
            else if (rdValue == 'noRadioChecked') {
                alert('no radio checked');
            }
        }
    </script>
</body>
</html>

You can also call the function within another function, like this:

function doSomething() {
    getRadioValue('theRadioGroupName');
    if (rdValue == '10') {
        // do something
    }
    else if (rdValue == 'noRadioChecked') {
        // do something else
    }  
} 
5

Assuming your form element is referred to by myForm variable below, and that your radio buttons share the name "my-radio-button-group-name", the following is pure JavaScript and standards compliant (although I have not checked it to be available everywhere):

myForm.elements.namedItem("my-radio-button-group-name").value

The above will yield the value of a checked (or selected, as it is also called) radio button element, if any, or null otherwise. The crux of the solution is the namedItem function which works with radio buttons specifically.

See HTMLFormElement.elements, HTMLFormControlsCollection.namedItem and especially RadioNodeList.value, as namedItem usually returns a RadioNodeList object.

(I use MDN because it allows one to track standards compliance, at least to a large degree, and because it is easier to comprehend than many WhatWG and W3C publications)

Armen Michaeli
  • 8,625
  • 8
  • 58
  • 95
  • When I wrote the answer I skimmed through existing answers, and did not see anything that resembled what I wanted to share. Now I see that I missed at least two similar solutions. Albeit, nobody wrote their code suggestion using the particular syntax I employ, but the general idea is the same. FYI. The point is to obtain the reference to a `RadioNodeList` through something like `form.elements[name]` or `form[name]` (maybe, a speculation) or through my above syntax. – Armen Michaeli Jun 04 '16 at 15:27
3

Directly calling a radio button many times gives you the value of the first button, not the checked button. Instead of looping through radio buttons to see which one is checked, I prefer to call an onclick JavaScript function that sets a variable that can later be retrieved at will.

<input type="radio" onclick="handleClick(this)" name="reportContent" id="reportContent" value="/reportFleet.php" >

Which calls:

var currentValue = 0;
function handleClick(myRadio) {
    currentValue = myRadio.value;
    document.getElementById("buttonSubmit").disabled = false;
}

An additional advantage being that I can treat data and/or react to the checking of a button (in this case, enabling the submit button).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tony gil
  • 9,424
  • 6
  • 76
  • 100
3

You can also loop through the buttons with a forEach-loop on the elements

    var elements = document.getElementsByName('radioButton');
    var checkedButton;
    console.log(elements);
    elements.forEach(e => {
        if (e.checked) {
            //if radio button is checked, set sort style
            checkedButton = e.value;
        }
    });
2

An improvement to the previous suggested functions:

function getRadioValue(groupName) {
    var _result;
    try {
        var o_radio_group = document.getElementsByName(groupName);
        for (var a = 0; a < o_radio_group.length; a++) {
            if (o_radio_group[a].checked) {
                _result = o_radio_group[a].value;
                break;
            }
        }
    } catch (e) { }
    return _result;
}
Dave
  • 1,823
  • 2
  • 16
  • 26
2

You can use .find() to select checked element:

var radio = Array.from(document.querySelectorAll('#rate input'))

var value = radio.length && radio.find(r => r.checked).value
Yukulélé
  • 15,644
  • 10
  • 70
  • 94
2

My take on this problem with pure JavaScript is to find the checked node, find its value and pop it out from the array.

var Anodes = document.getElementsByName('A'),
    AValue = Array.from(Anodes)
       .filter(node => node.checked)
       .map(node => node.value)
       .pop();
console.log(AValue);

Note that I'm using arrow functions. See this fiddle for a working example.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
pongi
  • 379
  • 1
  • 6
  • I would add a `tagName === 'INPUT'` check to make sure you're not working on any tags other than `input`. – Aternus Mar 12 '19 at 14:51
2

Here is a solution putting the radio buttons in a constant and getting the selected value only when needed.

const rates = document.forms.rates.elements["rate"]
showRate()
function showRate(){
    document.getElementById('results').innerHTML = rates.value
}
<form id="rates" onchange="showRate()">
  <input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
  <input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
  <input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate 
</form>
<div id="results"></div>
David Contreras
  • 169
  • 1
  • 3
1

If you are using jQuery:

$('input[name="rate"]:checked').val();

Maccath
  • 3,936
  • 4
  • 28
  • 42
0
<form id="rates">
  <input type="radio" name="rate" value="Fixed Rate"> Fixed
  <input type="radio" name="rate" value="Variable Rate"> Variable
  <input type="radio" name="rate" value="Multi Rate" checked> Multi
</form>

then...

var rate_value = rates.rate.value;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

Check a value by ID:

var CheckedValues = ($("#r1").is(':checked')) ? 1 : 0;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nabeel Iqbal
  • 71
  • 1
  • 12
0

I used the jQuery.click function to get the desired output:

$('input[name=rate]').click(function(){
  console.log('Hey you clicked this: ' + this.value);

  if(this.value == 'Fixed Rate'){
    rate_value = $('#r1').value;
  } else if(this.value =='Variable Rate'){
    rate_value = $('#r2').value;
  } else if(this.value =='Multi Rate'){
    rate_value = $('#r3').value;
  }

  $('#results').innerHTML = rate_value;
});
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Animesh Singh
  • 8,382
  • 1
  • 17
  • 20
0

If the buttons are in a form
var myform = new FormData(getformbywhatever); myform.get("rate");
QuerySelector above is a better solution. However, this method is easy to understand, especially if you don't have a clue about CSS. Plus, input fields are quite likely to be in a form anyway.
Didn't check, there are other similar solutions, sorry for the repetition

Kun Wang
  • 1
  • 2
0
var rates = document.getElementById('rates').value;

cannot get values of a radio button like that instead use

rate_value = document.getElementById('r1').value;
0

If you are using the jQuery, please use the bellow snippet for group of radio buttons.

var radioBtValue = $('input[type=radio][name=radiobt]:checked').val();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Surendra K
  • 56
  • 3
0

Simply use: document.querySelector('input[rate][checked]').value

mahdavipanah
  • 600
  • 5
  • 21
  • Did not work for me; see a similar syntax above from Pawan that did. As in, `document.querySelector('input[name = rate]:checked').value` – Tim Erickson Jun 04 '19 at 19:39
0

If you don't want it to fail if no value is checked yet, you can use the Optional chaining operator ?.:

document.querySelector('input[name="rate"]:checked')?.value

Optional chaining operator works in 92.35% of the browsers as per writing of this post August 22 2023 as per caniuse.

Wadih M.
  • 12,810
  • 7
  • 47
  • 57
-1

https://codepen.io/anon/pen/YQxbZJ

The HTML

<div id="rates">
    <input type="radio" id="x1" name="rate" value="Fixed Rate"> Fixed Rate
    <input type="radio" id="x2" name="rate" value="Variable Rate"
           checked="checked"> Variable Rate
    <input type="radio" id="x3" name="rate" value="Multi Rate" > Multi Rate
</div>

<button id="rdio"> Check Radio </button>
<div id="check">

</div>

The JavaScript

var x, y;
var x = document.getElementById("check");
function boom()
{
  if (document.getElementById("x1").checked)
    y = document.getElementById("x1").value;
  
  else if(document.getElementById("x2").checked)
    y = document.getElementById("x2").value;
  
  else if (document.getElementById("x3").checked)
    y = document.getElementById("x3").value;

  else
    y = "kuch nhi;"

  x.innerHTML = y;
}

var z = document.getElementById('rdio');
z.addEventListener("click", boom);`
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anshu
  • 29
  • 3
-1

   var rates=document.getElementsByName("rate");
            for (i = 0; i < rates.length; i++) {
            if (rates[i].checked) {
              console.log(rates[i].value);
              rate=rates[i].value;
              document.getElementById("rate").innerHTML = rate;
              alert(rate);
              
            }
          }
        <div id="rates">
          <input type="radio" id="r1" name="rate" value="Fixed Rate"> Fixed Rate
          <input type="radio" id="r2" name="rate" value="Variable Rate"> Variable Rate
          <input type="radio" id="r3" name="rate" value="Multi Rate" checked="checked"> Multi Rate  
        </div>
        </br>
        <div id='rate'>
        </div>
-3

In PHP, it's very easy.

HTML page

Male<input type="radio" name="radio" value="male"><br/>
Female<input type="radio" name="radio" value="female"><br/>
Others<input type="radio" name="radio" value="other"><br/>
<input type="submit" value="submit">

Take a value from a form to PHP:

$radio = $_POST['radio'];
use php if(isset($_POST['submit']))
{
    echo "you selected" . $radio . "thank you";
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131