How to use Dropdown values ​​in a table cell

I have an HTML table with some dropdowns in cells. I would like to access my dropdown options as I tried below. How can i do this? 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>
+4
source share
1 answer

Get all tritems in a table:

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

Then read valueeach selectin each line:

    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>
Run codeHide result
0
source

Source: https://habr.com/ru/post/1690969/


All Articles