2012-03-30 43 views
0

當我迭代一組輸入時,如果輸入是一組無線電的一部分,我怎麼能得到當前的無線電索引?獲取當前的無線電元素索引?

$('input').each(function(){ 

    if($(this).is(':radio')){ 
    // here get the index of the radio in the radio group, 
    // like 1, 2, 3 etc... 
    } 


}); 

索引應該是相對於無線電組,沒有整個輸入元素的集合。

該組由輸入名稱(具有相同名稱的輸入)確定。

+0

發佈一些我們可以使用的html – DG3 2012-03-30 15:23:10

+0

不會'$('input:radio')。each'比'$('input')。each'好嗎? – j08691 2012-03-30 15:27:32

+0

@ j08691只有當你只對迭代中的無線電輸入感興趣時,情況可能並非如此。 – 2012-03-30 15:37:44

回答

4

爲了找到radio的位置由radioname屬性定義的基團內:

$('input:radio').each(
    function(){ 
     console.log($(this).index('[name="' + this.name + '"]')); 
    });​ 

JS Fiddle proof of concept

參考文獻:

1
var inputs = $('input'); 

inputs.each(function() 
{ 
    if ($(this).is(':radio')) { 
    console.log(inputs.index(this)); 
    } 
});  
2
$('input:radio').each(function(el, i){ 
    //i is your index 
}); 

更新:我發現這個問題,以及查找無線電組的所選擇的值。 How can I know which radio button is selected via jQuery?

+0

+1,比我的回答好。你每天都會學到新的東西:-) – 2012-03-30 15:26:08

+0

你當然可以。 :) – Joe 2012-03-30 15:27:06

+1

我不是積極的,這實際上回答了這個問題。 – 2012-03-30 15:27:21