dumkat
dumkat

Reputation: 97

jQuery radio array selector

I have radio buttons like:

<input  type="radio" value="a" name="questions[0]">
<input  type="radio" value="b" name="questions[0]">
<input  type="radio" value="c" name="questions[0]">
<input  type="radio" value="d" name="questions[0]">

<input  type="radio" value="a" name="questions[1]">
<input  type="radio" value="b" name="questions[1]">
<input  type="radio" value="c" name="questions[1]">
<input  type="radio" value="d" name="questions[1]">

How do I loop through this with jQuery? I want validate that a response has been given for each question. Thanks.

edit: or is there even a way to get the length of the questions array?

Upvotes: 0

Views: 5053

Answers (3)

Felix
Felix

Reputation: 38102

You can do something like this:

var rgroups = [];
$('input:radio').each(function (index, el) {
    var i;
    for (i = 0; i < rgroups.length; i++)
    if (rgroups[i] == $(el).attr('name')) return true;
    rgroups.push($(el).attr('name'));
});
rgroups = rgroups.length;

$('#test').click(function () {
    if ($('input:radio:checked').length < rgroups) alert('You must fill in all the fields.');
    else alert("You're done!");
});

Fiddle Demo

Upvotes: 0

xdazz
xdazz

Reputation: 160833

$('[name="questions[1]"]:checked').val() gives the checked value of question 1.

Or like below, get the checked value with the name:

$('input[type=radio]:checked').each(function() {
  console.log($(this).val(), $(this).attr('name'));
});

Upvotes: 1

ltalhouarne
ltalhouarne

Reputation: 4636

 $("#myForm input[type=radio]").each(function() {

           //whatever you need     

 });

Upvotes: 1

Related Questions