简体   繁体   中英

How to acces values of Dropdown in a table cell

I have a HTML-table with some dropdowns in the cells. I would like to access the options of my dropdown like I tried below. How can I do that? My JavaScript doesn't seem to work.

<table id = "xy">
    <tr>
      <td>
        <select>
          <option>--Please Select--</option>
          <option>value 1</option>
          <option>value 2</option>
          <option>value 3</option>
       </select>
      </td>
    </tr>
    <tr>
     <td>
       <select>
          <option>--Please Select--</option>
          <option>value 1</option>
          <option>value 2</option>
          <option>value 3</option>
      </select>
     </td>
    </tr>
    </table>

    <script type="text/javascript">
        ...
        var table = document.getElementById("xy");

        for (var i = 0, row; row = table.rows[i]; i++) {
             alert(row.cells[0].innerHTML.options[0].value);
             alert(row.cells[1].innerHTML.options[0].value);
        }
        ...
    </script>

Get all tr elements in the table:

var selects = document.querySelectorAll('#xy tr');

Then read value s of each select in each row:

    var rows = document.querySelectorAll('#xy tr');
    for (var i = 0; i < rows.length; i++) { //iterate over rows
        var selects = rows[i].querySelectorAll('select');
        for (var j = 0; j < selects.length; j++) { //iterate over selects in a row
            console.log('Row number: ' + i);
            console.log(selects[j].value);
        }
    }

Example:

 function readValues() { var rows = document.querySelectorAll('#xy tr'); for (var i = 0; i < rows.length; i++) { var selects = rows[i].querySelectorAll('select'); for (var j = 0; j < selects.length; j++) { console.log('Row number: ' + i); console.log(selects[j].value); } } } 
 <table id = "xy"> <tr> <td> <select> <option>--Please Select--</option> <option>value 1</option> <option>value 2</option> <option>value 3</option> </select> </td> <td> <select> <option>--Please Select--</option> <option>value 1</option> <option>value 2</option> <option>value 3</option> </select> </td> </tr> <tr> <td> <select> <option>--Please Select--</option> <option>value 1</option> <option>value 2</option> <option>value 3</option> </select> </td> <td> <select> <option>--Please Select--</option> <option>value 1</option> <option>value 2</option> <option>value 3</option> </select> </td> </tr> </table> <button onclick="readValues()">Read values</button> 

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