HTML: Radio Button

By Xah Lee. Date: . Last updated: .

Here is how to create a HTML radio button selection input.

Result:

Only one can be selected (of the group that has the same name value name=val.).

<div>
<label><input type="radio" name="radioPets" value="dog">Dog</label>
<label><input type="radio" name="radioPets" value="cat" checked>Cat</label>
<label><input type="radio" name="radioPets" value="bird">Bird</label>
</div>
const radioPets = document.querySelectorAll('input[name="radioPets"]');
const showBox = document.getElementById("showBox");

const f_update = (() => {
  let selectedValue =
    document.querySelector('input[name="radioPets"]:checked').value;
  showBox.textContent = selectedValue;
});

Array.from(radioPets).forEach(
  ((x) => {
    x.addEventListener("input", f_update, false);
  }),
);

f_update();
BUY Ξ£JS JavaScript in Depth