Web Tools Table Maker3schools TranslateImage CompressorFavicon Icon GeneratorCrop & Resize Image
Apu
Apu January 27, 2023 › #Button #HowTo

Radio button validation in JavaScript

Are you looking for a way to validate radio buttons in JavaScript? If so, you’re in the right place.

In this article, we're going to talk about radio button validation in JavaScript for gender. Radio buttons are a great way to allow users to select one option from multiple options.

It's important that you make sure the user selects at least one option before submitting the form. Fortunately, we can easily do it with just a few lines of code.

First, we will create an HTML form with two radio buttons and an "Submit" button.

<form>  
 <input type="radio" class="male" name="gender" value="Male"> Male
 <input type="radio" class="female" name="gender" value="Female"> Female
 <button id="submit" type="button"> Submit </button>  
</form> 

Next, we will create a function that will check if any of these inputs were checked or not; this is where we'll do our validation logic:

document.getElementById("submit").addEventListener("click", function() { 
  const male = document.querySelector('.male');
  const female = document.querySelector('.female');
  if(!male.checked && !female.checked){
    alert('Please choose your Gender: Male or Female ')
  }else{
    alert('Form submitted!')
  }
}); 

Whenever, the submit button is clicked, an anonymous function is called. The function checks if neither the "Male" radio button nor the "Female" radio button is selected. If this is the case, a warning box with the message "Please choose your gender: male or female" is displayed. Otherwise, a message will be displayed with the text "Form submitted!".

Radio button validation without JavaScript. #

You don't need to write JavaScript code to check whether a radio button is selected or not.

Check one of them by default using the checked attribute and assign the same name to all radio buttons.

<form>  
 <input type="radio" name="gender" value="Male" checked=""> Male<br>
 <input type="radio" name="gender" value="Female"> Female<br>
 <input type="radio" name="gender" value="Other"> Other<br>
 <button type="button"> Submit </button>  
</form> 
save
listen
AI Answer
Write Your Answer
loading
back
View All