2014-02-20 52 views
0

我有一個單選按鈕:jQuery的無線電陣列選擇

<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]"> 

我如何遍歷這個使用jQuery?我想驗證每個問題的答案。謝謝。

編輯: 或者甚至有一種方式來獲得問題數組的長度?

回答

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

      //whatever you need  

}); 
+0

它可以更具體的名稱,即問題嗎? – dumkat

+0

您可以在循環中使用'$ this.attr('name')'。 – ltalhouarne

+0

'$(本).attr( '名')' –

1

$('[name="questions[1]"]:checked').val()給出了問題的檢查值1

或者像下面,名稱得到選中的值:

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

如果可能的話,需要循環遍歷它們而不知道有多少個問題。 – dumkat

+0

@dumkat查看修改。 – xdazz

0

你可以做這樣的事情:

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