How to get the selected radio button value using js [duplicate]
Asked Answered
T

19

54

I am using this code to get the value of currently selected radio button, but it doesn't work.

var mailcopy = document.getElementById('mailCopy').value; 

How to get the currently selected radio button value using Javascript?

Tiernan answered 6/10, 2010 at 4:40 Comment(0)
H
91

HTML

<p>Gender</p>
<input type="radio" id="gender0" name="gender" value="Male">Male<br>
<input type="radio" id="gender1" name="gender" value="Female">Female<br>

JS

var gender = document.querySelector('input[name = "gender"]:checked').value;
document.writeln("You entered " + gender + " for your gender<br>");
Houseman answered 22/7, 2013 at 20:28 Comment(1)
Lovely. And no need for a parent element.Lout
T
48

If you are using jQuery, following code will work for you.

$('input[name=radioName]:checked').val();
Triplane answered 24/9, 2012 at 10:49 Comment(0)
S
34

Radio buttons come in groups which have the same name and different ids, one of them will have the checked property set to true, so loop over them until you find it.

function getCheckedRadio(radio_group) {
    for (var i = 0; i < radio_group.length; i++) {
        var button = radio_group[i];
        if (button.checked) {
            return button;
        }
    }
    return undefined;
}
var checkedButton = getCheckedRadio(document.forms.frmId.elements.groupName);
if (checkedButton) {
    alert("The value is " + checkedButton.value);
}
Sarmentum answered 6/10, 2010 at 6:22 Comment(1)
Good for compatibility, this method works for older browsers too, pre HTML 5.Esmond
S
4

check this

<input class="gender" type="radio" name="sex" value="male">Male
<br>
<input class="gender" type="radio" name="sex" value="female">Female


<script type="text/javascript">
$(document).ready(function () {
$(".gender").change(function () {

    var val = $('.gender:checked').val();
    alert(val);
});
});

</script>

Example

Steinman answered 25/2, 2013 at 11:35 Comment(1)
my requirement is quite different, the alert box will come but at the click on the buttonAcescent
W
4

Maybe I'm missing something here, but wouldn't the good old standard JS work? I mean:

var selectedOption = document.getElementById('your-form-name')['radio-group-name'].value;

... which is only valid of course if have provided "value" for your radio input elements.

<input type="radio" name="radio-group-name" value="red" checked>
<input type="radio" name="radio-group-name" value="blue">

The value should be either 'red' or 'blue' in the above example.

Wellfound answered 17/1, 2016 at 11:48 Comment(0)
C
2
function getCheckedValue(radioObj, name) {

    for (j = 0; j < radioObj.rows.length; ++j) {
        for (k = 0; k < radioObj.cells.length; ++k) {
            var radioChoice = document.getElementById(name + "_" + k);
            if (radioChoice.checked) {
                return radioChoice.value;
            }
        }
    }
    return "";
}
Chirpy answered 24/9, 2012 at 10:45 Comment(0)
P
1

A simpler way of doing this is to use a global js variable that simply holds the id of the clicked radio button. Then you don't have to waste code spinning thru your radio lists looking for the selected value. I have done this in cases where I have a dynamically generated list of 100 or more radio buttons. spinning thru them is (almost imperceptible) slow, but this is an easier solution.

you can also do this with the id, but you usually just want the value.

<script>
var gRadioValue = ''; //global declared outside of function
function myRadioFunc(){
    var radioVal = gRadioValue;  
    // or maybe: var whichRadio = document.getElementById(gWhichCheckedId);
    //do somethign with radioVal
}
<script>

<input type="radio" name="rdo" id="rdo1" value="1" onClick="gRadioValue =this.value;"> One
<input type="radio" name="rdo" id="rdo2" value="2" onClick="gRadioValue =this.value;"> Two
...
<input type="radio" name="rdo" id="rdo99" value="99" onClick="gRadioValue =this.value;"> 99
Pirnot answered 30/8, 2013 at 17:58 Comment(0)
M
0

you can use this

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

or, for older version of jquery

$('input[@name="field_value"]:checked').val();
Mezzorilievo answered 20/6, 2013 at 6:7 Comment(0)
M
0

Since you want to get it using plain javascript, you can use the following code

var val = '';
if(document.getElementById('radio1').checked) {
  val = document.getElementById('radio1').value
}else if(document.getElementById('radio2').checked) {
  val = document.getElementById('radio2').value
}
Mellifluous answered 21/1, 2014 at 9:59 Comment(0)
C
0

Possibly not the most efficient way... but I have used an ID on each radio button (this is just because I'm not passing it as an actual form, it is just the raw fields).

I then call a function with a button, which checks each radio button to see if it is checked. It does this using the .checked function. If this is set to true I can change the value of another variable.

function createOutput() {
  var order = "in";
  if (document.getElementById('radio1').checked == true) {
    order = "pre";
  } else if (document.getElementById('radio2').checked == true) {
    order = "in";
  } else if (document.getElementById('radio3').checked == true) {
    order = "post";
  }
  document.getElementById('outputBox').innerHTML = order;
}
<input id="radio1" type="radio" name="order" value="preorder" />Preorder
<input id="radio2" type="radio" name="order" value="inorder" checked="true" />Inorder
<input id="radio3" type="radio" name="order" value="postorder" />Postorder
<button onclick="createOutput();">Generate Output</button>
<textarea id="outputBox" rows="10" cols="50"></textarea>

Hope this is useful, in someway,

Beanz

Chthonian answered 4/3, 2016 at 22:49 Comment(0)
F
0

You could do something very similar to Beanz's answer but instead of using IDs, use classes to reduce redundancy.

function getSelectedValue() {
  var radioBtns = document.getElementsByClassName("radioBtn");
  for(var i = 0; i < radioBtns.length; i++){
    if(radioBtns[i].checked){
      document.getElementById("output").textContent = radioBtns[i].value; 
    }
  }
}
<input class="radioBtn" type="radio" name="order" value="button1" />Button 1<br>
<input class="radioBtn" type="radio" name="order" value="button2" />Button 2<br>
<input class="radioBtn" type="radio" name="order" value="button3" />Button 3<br>
<button onclick="getSelectedValue();">Get Value of Selected Radio</button><br>
<textarea id="output"></textarea>
Fleer answered 24/11, 2016 at 23:7 Comment(0)
T
0

all of you can test this example and easy to understand.

        Name:   <input type="text" id="text" class ="input">
                <input type="text" id="text1" class ="input">
        Gender: <input type="radio" id="m" class="Rm"  name="Rmale" value="Male">
                <input type="radio" id="f" class="Rm" name="Rfemale" value="Female">
        Course: <input type="checkbox" id="math" class="cm" name="Cmath" value="Math">
                <input type="checkbox" id="physic" class="cm" name="Cphysic" value="Physic">
                <input type="checkbox" id="eng" class="cm"  name="Ceng" value="English">
        <button type="button" id="b1">show</button>

// javascript

    <script>
        function getData(input){
            return document.getElementById(input).value;
        }
        function dataByClassName(st){
            var value=document.getElementsByClassName(st)
            for(var i=0;i < value.length;i++){
                if(value[i].checked){
                    return value[i].value;
                }
            }
        }
        document.getElementById("b1").onclick = function ()
        {
            var st={
                name : getData("text")+getData("text1"),
                gender : dataByClassName("Rm"),
                course : dataByClassName("cm")
            };
            alert(st.name+" "+st.gender+" "+st.course);
        };

    </script>
Twosided answered 19/10, 2017 at 16:2 Comment(0)
F
0

Try this, I hope this one will work

function loadRadioButton(objectName, selectedValue) {

    var radioButtons = document.getElementsByName(objectName);

    if (radioButtons != null) {
        for (var radioCount = 0; radioCount < radioButtons.length; radioCount++) {
            if (radioButtons[radioCount].value == selectedValue) {
                radioButtons[radioCount].checked = true;
            }
        }
    }
}
Felike answered 23/11, 2018 at 9:25 Comment(0)
R
-1

If you can use jQuery "Chamika Sandamal" answer is the correct way to go. In the case you can't use jQuery you can do something like this:

function selectedRadio() {
    var radio = document.getElementsByName('mailCopy');
    alert(radio[0].value);
}

Notes:

  • In general for the inputs you want to have unique IDs (not a requirement but a good practice)
  • All the radio inputs that are from the same group MUST have the same name attribute, for example
  • You have to set the value attribute for each input

Here is an example of input radios:

<input type="radio" name="mailCopy" value="1" />1<br />
<input type="radio" name="mailCopy" value="2" />2<br />
Rupe answered 20/6, 2013 at 12:51 Comment(0)
S
-1

Use:

document.querySelector('#elementId:checked').value;

This will return the value of the selected radio button.

Sweetheart answered 19/4, 2020 at 12:3 Comment(0)
A
-1

Please try this:

this.template.querySelector('input[name = "gender"]:checked').value;
Amentia answered 17/9, 2022 at 20:11 Comment(0)
B
-2
var mailcopy = document.getElementById('mailCopy').checked; 

if(mailcopy==true)
{
  alert("Radio Button Checked");
}
else
{
  alert("Radio Button un-Checked");
}
Blister answered 6/10, 2010 at 5:7 Comment(1)
The question is looking to get the currently selected button, not find out if a specific button is checked.Sarmentum
S
-2

Hy, you have to do it this way.

function checkRadio () {
    if(document.getElementById('user1').checked) {
        return $('#user1').val();
    }else if(document.getElementById('user2').checked) {
        return $('#user2').val();
    }
}
Shelves answered 23/7, 2014 at 8:57 Comment(0)
O
-3

Use the element.checked property.

Oriental answered 6/10, 2010 at 4:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.