Reputation: 4883
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.
Upvotes: 488
Views: 1774275
Reputation: 11
if you want to know which radio is checked and which unchecked to take some actions ...
<input type="radio" id="a" onclick="changed(this)" name="radios" >one
<input type="radio" id="b" onclick="changed(this)" name="radios">two
<input type="radio" id="c" onclick="changed(this)" name="radios" >three
<input type="radio" id="d" onclick="changed(this)" name="radios" checked>four
radios = document.getElementsByName("radios")
var temp = setit()
function setit(){
var tmp = null
for (i=0;i<radios.length;++i)
if (radios[i].checked)
tmp=radios[i].id
return tmp
}
function changed(obj){
if(temp != obj.id){
if(temp)
previous(temp)
current(obj.id)
temp=obj.id
}
}
function previous(id){
alert("unchecked "+id)
}
function current(id){
alert("checked "+id)
}
Upvotes: 0
Reputation: 1428
Another (apparently older) option to retrieve the value is to use the format: "document.forms.nameOfTheForm.nameOfTheInput.value;" e.g. document.forms.mainForm.rads.value;
document.mainForm.onclick = function(){
var radVal = document.forms.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.
ref: Document: forms property - Web APIs | MDN
Fiddle here (works in Chrome and Firefox): https://jsfiddle.net/Josh_Shields/23kg3tf4/1/
Upvotes: 18
Reputation: 5024
RadioNodeList is now supported by all major browsers.
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.
Upvotes: 59
Reputation: 13452
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.
Upvotes: 5
Reputation:
<input type="radio" name="rdoName" value="YES"/>
<input type="radio" name="rdoName" value="NO"/>
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"
Upvotes: 11
Reputation: 1126
If you are using JavaScript without jQuery, you can use this command:
document.querySelector("input[type='radio'][name=rate]:checked").value;
Upvotes: 41
Reputation: 399
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.
Upvotes: 2
Reputation: 167
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>
Upvotes: 15
Reputation: 54
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();
Upvotes: 0
Reputation: 39
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);`
Upvotes: -1
Reputation: 9282
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;
});
Upvotes: 0
Reputation: 73
Check a value by ID:
var CheckedValues = ($("#r1").is(':checked')) ? 1 : 0;
Upvotes: 0
Reputation: 11
<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;
Upvotes: 0
Reputation: 9554
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).
Upvotes: 4
Reputation: 236
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>
Upvotes: 2
Reputation: 4252
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();
Upvotes: 326
Reputation: 92347
[...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>
Upvotes: 9
Reputation: 83
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;
}
});
Upvotes: 3
Reputation: 17052
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
Upvotes: 2
Reputation: 600
Simply use: document.querySelector('input[rate][checked]').value
Upvotes: 0
Reputation: 11
var rates = document.getElementById('rates').value;
cannot get values of a radio button like that instead use
rate_value = document.getElementById('r1').value;
Upvotes: 0
Reputation: 1
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
Upvotes: 0
Reputation: 357
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
Upvotes: 17
Reputation: 11646
This works in IE9 and above and all other browsers.
document.querySelector('input[name="rate"]:checked').value;
Upvotes: 792
Reputation: 3190
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
}
}
Upvotes: 5
Reputation: 1961
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;
}
Upvotes: 3
Reputation: 61
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
Upvotes: 6
Reputation: 6416
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;
}
}
Upvotes: 162