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.