2013-11-21 65 views
1

我想創建一個select下拉列表,其中包含列中的所有值,每個值只出現一次。JavaScript/jQuery:從列中獲取所有值而不重複

是否有一種方法可以在JavaScript或jQuery中實現這一點,假設我有一個基本的HTML表格並且所討論的列是columnA?非常感謝任何幫助,Tim。

+0

列的外觀如何? – adeneo

+1

[數組中唯一值]的可能重複(http://stackoverflow.com/questions/1960473/unique-values-in-an-array) – rolfv1

回答

5

你不得不一些檢查,以確保您尚未包含一列,喜歡的東西:

function makeSelectFromColumn() { 
    var arr = []; 
    $("td:first").each(function() { 
     if ($.inArray($(this).text(), arr) == -1) 
      arr.push($(this).text()); 
    }); 

    //Create your select 
    var select = $("<select />"); 
    for (var i = 0; i < arr.length; i++) { 
     $("<option>" + arr[i] + "</option>").appendTo(select); 
    } 

    select.appendTo("body"); //append where you need 
} 
+0

非常感謝 - 這是完美的! – user2571510

2

用純JS(無庫):live demo here (click).

var colA = document.querySelectorAll('td:first-child'); //select the column you want 

var used = []; //to check for used values 
var frag = document.createDocumentFragment(); //add option elements to this 
for (var i=0; i<colA.length; ++i) { //for each item in the column 
    var text = colA[i].textContent; //get the text from the item 
    if (used.indexOf(text) == -1) { //if the text isn't already used 
    used.push(text); //store the text as used 
    var option = document.createElement('option'); //create option 
    option.textContent = text; 
    frag.appendChild(option); //add option to frag 
    } 
} 

var select = document.createElement('select'); //create select 
select.appendChild(frag); //add options to select 

document.body.appendChild(select); //put the select somewhere on the page 

HTML :

<table> 
    <tbody> 
    <tr><td>Col A Val1</td></tr> 
    <tr><td>Col A Val2</td></tr> 
    <tr><td>Col A Val3</td></tr> 
    <tr><td>Col A Val1</td></tr> 
    <tr><td>Col A Val2</td></tr> 
    <tr><td>Col A Val3</td></tr> 
    </tbody> 
</table> 
+0

非常感謝 - 這太棒了!我會試着看看哪一個更好。 – user2571510

+0

@ user2571510都可以正常工作,但沒有理由僅僅爲此使用jQuery。如果您已經在使用jQuery,那麼您還可以使用jQuery解決方案。如果你不使用jQuery,請使用我的方法。一般來說,如果可能的話,最好給出不使用庫的答案。 – m59

0
function getNthColumn(n) { 

    var data = [], 
     i, 
     yourSelect, 
     unique; 

    $("#yourTable tr td:nth-child("+n+")").each(function() { 
     data.push($(this).text());   
    }); 

    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter 
    // Use this function if your table is not large as the time complexity is O(n^2) 
    unique = data.filter(function(item, i, arr) { 
     return i == arr.indexOf(item); 
    }); 

    yourSelect = $('#yourSelect'); 
    for (i = 0; i < unique.length; i += 1) { 
     yourSelect.append("<option>"+unique[i]+"</option>"); 
    } 
} 

http://jsfiddle.net/xaum3/2/

相關問題