简体   繁体   中英

How to filter data of a html-table with a drop-down-menu with javascript

I have a html-file which makes a table with 3 columns and dynamic rows. The data for the table will be read in from a java project. The java project doesn't matter here. I also did a drop-down-menu on my table for the first column with two entries. Now I would like to filter my table when I choose one entry of the drop-down-menu. How can i do that? How do I need to use JavaScript here?

See the code below (only html because I don't know what to do in Javascript)

<table>
    <colgroup>
        <col width="150" style="background-color:red"></col>
        <col width="165"></col>
    </colgroup>
    <tr  style ="background-color:grey">
        <th>
            Plane
            <select size="2" name="choice">
                <option selected="selected">number_1</option>
                <option>number_2</option>                       
            </select>                   
        </th>   
        <th>date</th>
        <th>addition</th>
    </tr>


    <xsl:for-each select="logstore/plane/trigger">
    <tbody>
        <tr>
            <td><xsl:value-of select="../name"/></td>
            <td><xsl:value-of select="date"/></td>
            <td><xsl:value-of select="addition"/></td>
        </tr>
    </tbody>
    </xsl:for-each>
</table>

You can do it like this:

(adapted from this tutorial , with the input element replaced by a select element and the onkeyup attribute replaced by oninput -- See comments in the code for further explanation of how it works)

 function filterTable() { // Variables let dropdown, table, rows, cells, country, filter; dropdown = document.getElementById("countriesDropdown"); table = document.getElementById("myTable"); rows = table.getElementsByTagName("tr"); filter = dropdown.value; // Loops through rows and hides those with countries that don't match the filter for (let row of rows) { // `for...of` loops through the NodeList cells = row.getElementsByTagName("td"); country = cells[1] || null; // gets the 2nd `td` or nothing // if the filter is set to 'All', or this is the header row, or 2nd `td` text matches filter if (filter === "All" || !country || (filter === country.textContent)) { row.style.display = ""; // shows this row } else { row.style.display = "none"; // hides this row } } } 
 <select id="countriesDropdown" oninput="filterTable()"> <option>All</option> <option>Sweden</option> <option>Germany</option> </select> <table id="myTable"> <tr><th>Name</th><th>Country</th></tr><!-- header row uses 'th' instead of 'td' --> <tr><td>Inga</td><td>Sweden</td></tr> <tr><td>Helena</td><td>Sweden</td></tr> <tr><td>Hans</td><td>Germany</td></tr> <tr><td>Anna</td><td>Germany</td></tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM