yoda
yoda

Reputation: 569

Checking all radio button are checked in native javascript

I have a gatherRadioBtn() function which posts form else displays error in page. This takes cue from checkRadioWrapper() to check if all radio buttons are checked.

However, the true condition does not materialize. Is there a mistake in my (r[i].type == "radio") && !(r[i].checked) expression.

Will upload on jsfiddle soon

Thanks.

function checkRadioWrapper()
{
    for (var i=0; i < r.length; i++)
    {
        if (  (r[i].type == "radio") && !(r[i].checked) )
        {
            return false;   
        }
    }

    return true;
}

function gatherRadioBtn()
{
    alert("in gather");
    var r = document.getElementsByTagName("input");
    var literal = [];

    for (var i=0; i < r.length; i++)
    {
        if (  (r[i].type == "radio") && r[i].checked )
        {
            literal.push(r[i].name);
            literal.push(r[i].value);
        }
    }

    if (checkRadioWrapper())
    {
        document.getElementById("Errnodata").innerHTML = "" ;  
        var joinedArray = literal.join(", ");
        window.opener.document.getElementById("myarray").value= joinedArray;
        window.opener.getVolunteerDetails();
        window.close();
    }
    else
    {
       document.getElementById("Errnodata").innerHTML = "Please select for every radio btns!" ;  
    }
}

Upvotes: 0

Views: 404

Answers (1)

Pointy
Pointy

Reputation: 413996

You'll have to pass "r" as a parameter to your function:

function checkRadioWrapper( r )
{
    for (var i=0; i < r.length; i++)
      // etc

and then:

if (checkRadioWrapper( r ))

Now, that said, in a group of radio buttons sharing the same name, the browser will never allow all of them to be checked at the same time. Thus, this really doesn't make a lot of sense. If you've got radio buttons that don't share a name with other radio buttons, they should be checkboxes and not radio buttons.

Upvotes: 2

Related Questions