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.
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.
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);
}
<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.”
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
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.