javascriptjqueryhtmlselect

Get all values from column without duplicates in JavaScript / jQuery


I would like to create a select dropdown that contains all values from a column with each value only appearing once.

Is there a way to achieve this in JavaScript or jQuery assuming I have a basic HTML table and the column in question is columnA ?


Solution

  • You'd have to some checking to be sure you haven't already included a column, something like:

    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
    }