user2108171
user2108171

Reputation: 21

Validating multiple sets of radio buttons

I have a form with 29 selections of radio button pairs, each with a Yes/No selection.

The names of the selections increment like this for each set: ans1, ans2, ans3... ans29. Each one have a value of "yes" or "no"

It follows more or less like this:

<input type="radio" id="yes1" name="ans1" value="yes"/>
<input type="radio" id="no1" name="ans1" value="no"/>

I want to write a Javascript function to validate the answers when submitting the form. I was thinking of using array's within a loop, but have no idea how to get the selections into an array.

The obvious long method is a repetitive if(ans1 = yes) {do something} if(ans2=yes){do something}. I have seen examples of getElementsByName but is not sure how to implement it in a simple loop function to test for each and every iteration.

Upvotes: 2

Views: 301

Answers (2)

Daniil Grankin
Daniil Grankin

Reputation: 3933

use jquery (http://jquery.com/) like

for(int i = 1; i < 30; ++i)
{
    if ($('#yes' + i).val() == 'yes'){ do something }
}

Upvotes: 1

emesx
emesx

Reputation: 12755

Using jQuery

$("input:radio:checked").each(function (index) {
    var this$ = $(this);
    var q = this$.attr('name');
    var a = this$.val();

    console.log('Question: ' + q + ', answer: ' + a);
});

This snippet selects only checked radio buttons and then prints them to the console. You can do whatever you want from here, q is the name of the question (e.g. ans1) and a is the answer itself (i.e. true of false).

See it in action.

Upvotes: 5

Related Questions