2011-12-05 162 views
0

我的HTML頁面上有一堆收音機框。有點像這樣:獲取所有選中值的列表

<input type="radio" name="19" class="custom" value="1"/> 
<input type="radio" name="19" class="custom" value="2"/> 
<input type="radio" name="19" class="custom" value="3"/> 

<input type="radio" name="20" class="custom" value="4"/> 
<input type="radio" name="20" class="custom" value="5"/> 
<input type="radio" name="20" class="custom" value="6"/> 

<input type="radio" name="21" class="custom" value="7"/> 
<input type="radio" name="21" class="custom" value="8"/> 
<input type="radio" name="21" class="custom" value="9"/> 

選擇所有的收音機後,用戶點擊一個按鈕。使用Javascript或Jquery,我如何創建一個數組對象來保存所有選中的框的值?

我有一個數組(questionsArray),它包含無線電框集的name值。

我試着這樣做:

for (var i=0; i<questionsArray.length; i++) 
{ 
    document.write(document.getElementsByName(questionsArray[i])[0].value + "<br/>"); 
} 

這不僅拋出異常cannot access value of undefined,它不是將它們添加到一個數組無論是。

任何幫助將不勝感激。

+0

你應該檢查的http:// api.jquery.com/serializeArray/ –

回答

4

下面將把value屬性的值爲每個選定的單選按鈕進入arr陣列:

var arr = []; 
$(".custom:checked").each(function() { 
    arr.push($(this).val()); 
}); 
+0

完美的作品! – Zabs

0
$('#my-button-id').click(function() { 
    var tmp = ''; 
    $('.custom:checked').each(function() { 
     // Do what you want... 
     tmp += ' ' + $(this).val(); 
    }); 
    alert(tmp); 
}); 
+0

對不起,這個非常基本的問題,但代碼將進入映射到最終按鈕的'onclick'函數? – xbonez

0

試試這個代碼

$('#buttonId').click(function() { 
    var result = ''; 
    $('input:checked').each(function() { 
     result += ',' + $(this).val(); 
    }); 
    alert(result); 
}); 
相關問題