I want to get the selected value from a group of radio buttons.
Here\'s my HTML:
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.
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 JS
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);`
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;
}
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