2013-12-03 46 views
0

問:確定多個選擇列表是否具有相同的最簡單/最有效的方法是什麼selectedIndex檢查SelectedIndex匹配多個選擇

背景資料: 我有一個頁面上的多個(最多200)選擇列表 - 所有類tariff,我需要檢查,他們都具有相同的selectedIndex

我的第一種方法是使用循環每錄製前值 - 確保每一個選擇匹配的 - 但它只是似乎效率不高。例如

var tariffSelected; 
var first = true; 
$('.tariff').each(function() { 
    if (first) { 
     // store first value 
     tariffSelected = $(this).prop('selectedIndex'); 
     first = false; 
    } 
    if (tariffSelected !== $(this).prop('selectedIndex')) { 
     // they don't match 
    } 
}); 

回答

2

我只想確認選擇的數量是一樣的選擇與selectedIndex處的數匹配第一個選擇,例如:

var allTariffs = $('.tariff'); 
var indexToMatch = allTariffs.eq(0).prop('selectedIndex'); 

var matchingTariffs = allTariffs.filter(function() { 
    return $(this).prop('selectedIndex') === indexToMatch; 
}); 

var allMatch = allTariffs.length === matchingTariffs.length; 
+0

+1正是我一直在尋找...感謝(當計時器到期會接受) – ManseUK

+1

'matchingTariffs.length'? ? –

+0

@ A.Wolff剛剛注意到,當我測試它時... – ManseUK

1

這裏是一個工作示例

http://jsfiddle.net/q89Tf/

var s = $("select.tariff"); 
var firstVal = $("select").first().prop("selectedIndex"); 
var ss = $('select').filter(function() { 
    return this.selectedIndex === firstVal; 
}).length === s.length; 
+0

不知道爲什麼這會被低估 - 看起來工作正常...... +1謝謝 – ManseUK

+0

我低估了這一點,因爲它與我的答案完全一樣(與之後17分鐘。 – jbabey

+0

對不起,我真的沒有複製你,我開始研究它,並沒有刷新頁面之前發佈。 –