如何获取表中的输入值?

时间:2019-05-12 19:42:59

标签: javascript html

我有一个带有动态行的表,每行在其按钮旁边(在第三个单元格中)都包含一个输入。

下面的代码代表我的表的一行:

window.getKey = function(ele) {

  var row = ele.closest('tr');

  console.log("cell 0: " + row.cells[0].textContent);
  console.log("cell 1: " + row.cells[1].textContent);
  console.log("cell 2: " + row.cells[2].children[0].value);
}
<table class="table table-striped table-bordered text-center table-hover" id="tbl_posts">
  <tr class="satr">
    <th class="colu">Username</th>
    <th class="colu">Post</th>
    <th class="colu">Decode</th>
  </tr>
  <tr>
    <td>
      <p>Mike</p>
    </td>
    <td>
      <p>Content</p>
      <td>
        <div>
          <input id="key_input" type="number" placeholder="Enter number" />
          <div>
            <button class="btn btn-outline-secondary" id="decode" type="submit" onclick="getKey(this)">Decode</button>
          </div>
        </div>
      </td>

如您所见,console.log()显示了除第三个单元格以外的其他单元格的内容。 其他问题对我没有帮助(例如:How to retrieve value of input type in a dynamic table

如何访问第三个单元格中的输入值?

1 个答案:

答案 0 :(得分:2)

根据您的HTML代码,row.cells[2].children[0].value获得div而不是input的值。要获取input的值,可以使用:

  • row.cells[2].children[0].children[0].value
  • row.cells[2].querySelector("input").value

代码:

window.getKey = function(ele) {
  var row = ele.closest('tr');

  console.log("cell 0: " + row.cells[0].textContent);
  console.log("cell 1: " + row.cells[1].textContent);
  console.log("cell 2: " + row.cells[2].querySelector("input").value);
}
<table class="table table-striped table-bordered text-center table-hover" id="tbl_posts">
  <tr class="satr">
    <th class="colu">Username</th>
    <th class="colu">Post</th>
    <th class="colu">Decode</th>
  </tr>
  <tr>
    <td>
      <p>Mike</p>
    </td>
    <td>
      <p>Content</p>
    </td>
    <td>
      <div>
        <input id="key_input" type="number" placeholder="Enter number" />
        <div>
          <button class="btn btn-outline-secondary" id="decode" type="submit"
              onclick="getKey(this)">Decode</button>
        </div>
      </div>
    </td>
  </tr>
</table>