How to Check if One Radio Button in Each Group is Checked using jQuery


Before submitting the value of the radio button group, it is required to check whether the user selects one radio button in each group. Because it’s always a good idea to validate the value in the client before sending data to the server side. Using jQuery you can easily check if radio is checked. But sometimes you need to validate whether the radio button in multiple groups is checked or not. Don’t worry, here we will show you how to check if one radio button in each group is checked using jQuery.

In the example script, there are three questions and each question has two radio buttons to select an option. Now before submitting the user input, we will check if one radio button in each group is checked using jQuery.

HTML

<h1>Question 1</h1>
<input type="radio" name="ques1" value="1" />Option 1
<input type="radio" name="ques1" value="2" />Option 2

<h1>Question 2</h1>
<input type="radio" name="ques2" value="1" />Option 1
<input type="radio" name="ques2" value="2" />Option 2

<h1>Question 3</h1>
<input type="radio" name="ques3" value="1" />Option 1
<input type="radio" name="ques3" value="2" />Option 2

<input type="button" id="radioValidate" value="Validate"/>

JavaScript

$(document).ready(function(){
    $('#radioValidate').click(function(){
        var check = true;
        $("input:radio").each(function(){
            var name = $(this).attr("name");
            if($("input:radio[name="+name+"]:checked").length == 0){
                check = false;
            }
        });
        
        if(check){
            alert('One radio in each group is checked.');
        }else{
            alert('Please select one option in each question.');
        }
    });
});

Leave a reply