JS DOM: input radio button 🔘
What is Radio Buttons
Radio Buttons is a group of buttons that only one can be activated.
The name came from the row of buttons on radio of cars around 1970s. These buttons, once pressed, it remains physically sunk, and pops up all other buttons.
Radio Buttons Example
Here is how to create a HTML radio button selection input.
Result:
Code
Only one can be selected (of the group that has the same name value name=val.).
<div> <label><input type="radio" name="pets_XDbSr" value="dog">Dog</label> <label><input type="radio" name="pets_XDbSr" value="cat" checked>Cat</label> <label><input type="radio" name="pets_XDbSr" value="bird">Bird</label> </div>
"use strict"; const petsRadioGroup = document.querySelectorAll(`input[name="pets_XDbSr"]`); if (petsRadioGroup.length === 0) throw (new Error(`missing input[name="pets_XDbSr"]`)); const output_zHrRz = document.getElementById("output_zHrRz"); if (output_zHrRz === null) throw new Error("id output_zHrRz missing"); const f_update = () => { const isChecked = document.querySelector('input[name="pets_XDbSr"]:checked'); if (isChecked === null) throw (new Error(`input[name="pets_XDbSr"] none checked.`)); const selectedValue = isChecked.value; output_zHrRz.textContent = selectedValue; }; for (const x of petsRadioGroup) { x.addEventListener("change", f_update); } f_update();