jQuery - Check if multiple radio button groups are selected, then return name of those who aren't

12,507

You have to traverse each div with class aQuestion by using .each() and you need to check whether any radio buttons are checked inside that of element by using .find().

Try,

$('.aQuestion').each(function(){
  if($(this).find('input[type="radio"]:checked').length > 0)
    {
       alert("checked");
    }
  else
    {
       alert("not checked");
    }    
});

As mplungjan suggested you can also use,

$('.aQuestion').each(function(){ 
  $(this).toggleClass("didntmakechoice",$(this).find('input[type="radio"]:checked').length == 0);
}); 
Share:
12,507
RedHawkDK
Author by

RedHawkDK

Updated on June 09, 2022

Comments

  • RedHawkDK
    RedHawkDK almost 2 years

    I have +90 questions in a survey. Each question has 5 choices. The questions is built by database information.

    I need to check if all the questions were answered, and if one of them wasn't, then this should be alerted.

    They are all divided into radio button groups, and I would like to use jQuery to check.

    The if statement won't work, the only think that gets alerted is: " is NOT checked!"

    <div class='aQuestion' id='div1'>
        <STRONG>1. </STRONG>
        <STRONG>Question</STRONG></br>
        <INPUT TYPE='radio' NAME='grp1' VALUE='0'>answer 1</br>
        <INPUT TYPE='radio' NAME='grp1' VALUE='1'>answer 2</br>
        <INPUT TYPE='radio' NAME='grp1' VALUE='2'>answer 3</br>
        <INPUT TYPE='radio' NAME='grp1' VALUE='3'>answer 4</br>
        <INPUT TYPE='radio' NAME='grp1' VALUE='4'>answer 5
    </div>
    
    <div class='aQuestion' id='div2'>
        <STRONG>2. </STRONG>
        <STRONG>Question</STRONG></br>
        <INPUT TYPE='radio' NAME='grp2' VALUE='0'>answer 1</br>
        <INPUT TYPE='radio' NAME='grp2' VALUE='1'>answer 2</br>
        <INPUT TYPE='radio' NAME='grp2' VALUE='2'>answer 3</br>
        <INPUT TYPE='radio' NAME='grp2' VALUE='3'>answer 4</br>
        <INPUT TYPE='radio' NAME='grp2' VALUE='4'>answer 5
    </div>
    

    ( And there are 8 more those questions as above )

    <script>
    
        jQuery('#submit').click(function(event)
        {
            event.preventDefault();
    
            for(i=1;i<=10;i++)
            {               
                var currentGroup = "grp" + i;
    
                if($("input[name=currentGroup]:checked").val())
                {
                    alert(currentGroup + ' is checked!');                
                }
                else 
                {
                    alert(currentGroup + ' is NOT checked!');
                }    
            }
        });
    
    </script>
    

    Thanks in advance. And if anyone has an idea how to make users browser view jump to the questions that weren't answered, then I would like to hear that too ;)