Search code examples
javascriptunderscore.jstabular

How can I select multiple items in a table using Javascript


Using a example like this:

http://www.datatables.net/media/blog/bootstrap_2/

How could I select for, not filter, Firefox and Mozilla in a table. I was thinking of using select2.js to get multiple selected items. then processing the table with underscore...If there is blog, explaining this please list.


Solution

  • I think what you are asking is:

    I have a table and a multiple selection box. I want to use the users' selections in the multiple selection box to filter the rows of the table. If nothing is selected, all rows display. If two options are selected, only rows that correspond to those two options display. How can I do this?

    This works:

    HTML

    <select id="browserSelect" multiple style="width:300px">
        <option value="Firefox">Firefox</option>
        <option value="Mozilla">Mozilla</option>
        <option value="IE">IE</option>
        <option value="Netscape">Netscape</option>
        <option value="Opera">Opera</option>
    </select>
    <table>
        <tr>
            <td>Firefox</td>
            <td>details</td>
        </tr>
        <tr>
            <td>IE</td>
            <td>details</td>
        </tr>
        <tr>
            <td>Firefox</td>
            <td>more details</td>
        </tr>
        <tr>
            <td>Netscape</td>
            <td>details</td>
        </tr>
        <tr>
            <td>Mozilla</td>
            <td>details</td>
        </tr>
        <tr>
            <td>Opera</td>
            <td>details</td>
        </tr>
    </table>
    

    JS with jQuery and Select2:

    $("#browserSelect").select2().change(function () {
        var selectedBrowsers = $('select').val();
        if (selectedBrowsers) {
        //If the user made a selection, hide every row of the table
            $('tr').hide();
            //Show only rows where the text in the first column
            //corresponds to one of the user's selections
            $('td:first-child').each(function (i, cell) {
                if (selectedBrowsers.indexOf($(cell).text()) > -1) {
                    $(cell).parent().show();
                }
            });
        } else {
        //Show all rows when there is no selection
            $('tr').show();
        }
    });
    

    http://jsfiddle.net/Q526A/3/

    I used Select2 to make the multiple selection box more user-friendly, as you suggested.