JavaScript Radio Button Validation

Radio buttons are used when a user should choose exactly one option from a group. All buttons in the group share the same name; the browser then allows only one of them to be checked at a time.

<label><input type="radio" name="payment" value="cash" required> Cash</label>
<label><input type="radio" name="payment" value="card"> Card</label>
<label><input type="radio" name="payment" value="transfer"> Bank transfer</label>

If one choice is required, native HTML validation can often handle the rule by adding required to one radio button in the group. JavaScript is useful when you need custom feedback or must use the selected value in other logic.

Open radio-button validation demo
Table of Contents

Get the Checked Radio Button Top ↑

const selected = document.querySelector('input[name="payment"]:checked');
if (selected) {
  console.log(selected.value);
}

querySelector() returns the checked item or null when nothing is selected, which makes the validation condition direct.

Use getElementsByName() for the Group Top ↑

The original tutorial uses getElementsByName() to collect radio buttons sharing a name. That remains valid.

const radios = document.getElementsByName("payment");
const selected = [...radios].find((radio) => radio.checked);
if (selected) {
  console.log(selected.value);
}

Use Native required Validation for a Simple Rule Top ↑

<input type="radio" name="gender" value="male" required> Male
<input type="radio" name="gender" value="female"> Female

The browser blocks submission until one radio in the group is selected. This is usually preferable when the only rule is “choose one.”

Validate the Radio Group on Submit Top ↑

const form = document.getElementById("paymentForm");
const message = document.getElementById("message");

form.addEventListener("submit", (event) => {
  const selected = document.querySelector('input[name="payment"]:checked');
  if (!selected) {
    event.preventDefault();
    message.textContent = "Select a payment method before submitting.";
    return;
  }
  message.textContent = `Selected: ${selected.value}`;
});

As with all client-side validation, important rules should also be checked on the server. The original page’s links to server-side validation, JavaScript support detection, and enable JavaScript guidance are retained.

Radio button onclick event · Checkbox validation · Listbox validation · AJAX form validation · AJAX form validation II

JavaScript validation Listbox validation




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer