Search code examples
javascriptformsvalidationradio-button

Validation of 2 or more groups of radio buttons each containing 4 radios


So I had to include this part in one of our class projects. We were asked to create a quiz webpage with radios and checkboxes, and then to write a JavaScript function to validate the radios. Now, I know that these radios can be verified easily by individuals for loops for each group, but that doesn't sound practical when I have a large number of these groups in my code. So I tried the following code:-

function quizRadioFilled() 
{
    var check = false;
    var c = 0;
    var x = 0;
    var radiob = [];
    radiob[0] = document.getElementsByName('q1');
    radiob[1] = document.getElementsByName('q2');
    radiob[2] = document.getElementsByName('q3');
    radiob[3] = document.getElementsByName('q4');
    radiob[4] = document.getElementsByName('q5');
    radiob[5] = document.getElementsByName('q9');
    radiob[6] = document.getElementsByName('q10');
    for(var i = 0; i <= 6; i++)
    {
        for(var j = 1; j <= radiob[i].length; j++)
        {
            if(radiob[i].checked)
            {
                c = 1;
                break;
            }
        }
        if(c == 0)          
        {
            check = false;
        }
    }
    if(!check)
    {
        alert('Please attempt all the questions....');
    }
}

I first stored the names of each group in an array. Then looped through this to validate each of these groups. I want to display the alert if a group has no radio button selected. But I am not getting the required result. Though I have completed this project now, I would still like to get this function to work. Kindly provide some suggestions.


Solution

    • You never set check to true anywhere, so it is always false.
    • radiob[i] is an array (or, more precisely, a NodeList), so radiob[i].checked is always undefined.
    • Arrays in JavaScript start indexing at 0, and this applies to NodeList as well. So your for (var j = 1; j <= radiob[i].length; j++) loop is not correct.

    If you fix these problems then your function should work correctly.