I have two radio buttons within an HTML form. A dialog box appears when one of the fields is null. How can I check whether a radio button is selected?
If you want vanilla JavaScript, don't want to clutter your markup by adding IDs on each radio button, and only care about modern browsers, the following functional approach is a little more tasteful to me than a for loop:
If neither is checked, it will return undefined
(though you could change the line above to return something else, e.g., to get false
returned, you could change the relevant line above to: }).pop() || {value:false}).value;
).
There is also the forward-looking polyfill approach since the RadioNodeList interface should make it easy to just use a value
property on the list of form child radio elements (found in the above code as formElement[radioName]
), but that has its own problems: How to polyfill RadioNodeList?