Back to blog
Feb 14, 2025
2 min read

How to validate Radio buttons using javascript

Quick and easy way to validate radio buttons using only a few lines of javascript

To validate radio buttons in JavaScript, you typically want to check whether a user has selected an option before submitting a form. Here’s an example of how you can validate radio buttons:



<form id="myForm" onsubmit="return validateForm()">
  <label>
    <input type="radio" name="choice" value="option1" onclick="clearError()"> Option 1
  </label>
  <label>
    <input type="radio" name="choice" value="option2" onclick="clearError()"> Option 2
  </label>
  <label>
    <input type="radio" name="choice" value="option3" onclick="clearError()"> Option 3
  </label>

  <span id="error-message" style="color:red; display:none;">Please select an option.</span>

  <button type="submit">Submit</button>
</form>


function validateForm() {
	// Get all radio buttons with name 'choice'
	var radios = document.getElementsByName("choice");

	// Flag to check if any radio button is selected
	var isSelected = false;

	// Loop through the radio buttons to check if any is selected
	for (var i = 0; i < radios.length; i++) {
		if (radios[i].checked) {
			isSelected = true;
			break;
		}
	}

	// If none is selected, display error message and return false to prevent form submission
	if (!isSelected) {
		document.getElementById("error-message").style.display = "inline";
		return false;
	}

	// If selected, return true to allow form submission
	return true;
}

function clearError() {
	// Hide the error message when any radio button is clicked
	document.getElementById("error-message").style.display = "none";
}

Changes:

  • HTML: I added the onclick="clearError()" to each radio button, so whenever a user clicks on a radio button, the clearError() function is called.
  • JavaScript: The clearError() function will hide the error message by setting the display style to none.

How it works:

  1. When the form is submitted, it checks whether any radio button is selected.
  2. If none are selected, the error message appears.
  3. If the user clicks on any radio button, the clearError() function is triggered, which hides the error message.
  4. If the form is submitted after selecting a radio button, the form will be submitted normally, without the error message.

This will ensure the error message disappears when the user selects a radio button.