2009-08-06 113 views
17

我正在寻找一种方法来使用jQuery从表列中填充具有唯一值的选择框。到目前为止,我的尝试是徒劳的,但我对前端开发相对较新,所以我希望有人能向我展示灯光。jquery从表列中获取所有值

干杯。

+4

向我们展示您到目前为止所得到的结果以及您遇到的问题。此外,还包括表格的示例源代码。 – 2009-08-06 09:44:23

回答

40

这应该让你开始。请注意,我将该单元格内容用于该选项的值和文本。你可能需要改变这个,但从这个问题还不清楚。

var items=[], options=[]; 

//Iterate all td's in second column 
$('#tableId tbody tr td:nth-child(2)').each(function(){ 
    //add item to array 
    items.push($(this).text());  
}); 

//restrict array to unique items 
var items = $.unique(items); 

//iterate unique array and build array of select options 
$.each(items, function(i, item){ 
    options.push('<option value="' + item + '">' + item + '</option>'); 
}) 

//finally empty the select and append the items from the array 
$('#selectId').empty().append(options.join()); 
+0

在项目分配中缺少一个= = – 2009-08-06 10:10:53

+0

Cheers Russ,好现场 – redsquare 2009-08-06 10:12:17

+0

@redsquare 我在这里搜索了一些相同的东西。如何为该值设置辅助数组? options.push(''); – trobbins26 2012-11-29 06:04:54

2

你可以使用jQuery的每个函数:

function FillSelect(){ 
    var vals = new Array(); 
    var i=0; 
    var options=''; 
    $("#tbl tr:gt(0) td:nth-child(2)").each(function(){ 
     var t=$(this).html(); 
     if($.inArray(t, vals) < 0) 
     { 
      vals[i]=t; 
      i++; 
     } 
    }); 

    for(var j=0;j<i;j++) 
    { 
     options += '<option value="' + j + '">' + vals[j] + '</option>'; 
    } 

    $("#sel2").html(options); 
} 

假设 'TBL' 是你的表的ID,“选择要填充的sel2'is ID。如果您不想排除第一行,那么您可以删除tr:gt(0)并将简单的tr置于选择器表达式中。

+0

使用tbody作为标题行应该是一个thead – redsquare 2009-08-06 10:08:01