25

I'm looking for a way to populate a select box with unique values from a table column using jQuery. So far my attempts have been futile but I am relatively new to front end development so I'm hoping someone can show me the light.

Cheers.

1
  • 5
    Show us what you've got so far, and what problems you've encountered. Also, include sample source code for the table. Aug 6, 2009 at 9:44

2 Answers 2

59

This should get you started. Note that I use the cell contents for both the value and the text of the option. You may need to change this but it is unclear from the question.

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() );
6
  • missing an = in the items assignment
    – Russ Cam
    Aug 6, 2009 at 10:10
  • @redsquare I came accross this in search for sort of the same thing. How would emplament a secondary array for the value? options.push('<option value="' + link + '">' + item + '</option>');
    – trobbins26
    Nov 29, 2012 at 6:04
  • @trobbins26 sorry, I do not understand what you mean - " secondary array for the value"
    – redsquare
    Nov 29, 2012 at 9:35
  • @redsquare Sorry... my ultimate goal is to pass table td:first-child to the option value, and pass table td:nth-child(2) to the options inner html text.
    – trobbins26
    Nov 29, 2012 at 15:53
  • Thanks, This gives me an idea to the current problem that I'm facing. Jul 17, 2019 at 8:25
2

you can use jquery's each function:

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);
}

suppose 'tbl' is ID of your table, 'sel2'is id of select you want to populate. If you don't want to exclude first row then you can remove tr:gt(0) and put simple tr in selector expression.

1
  • use tbody as the header row should be a thead
    – redsquare
    Aug 6, 2009 at 10:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.