【问题标题】:How to get the input value in a table?如何获取表格中的输入值?
【发布时间】:2019-05-13 05:31:18
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    根据您的 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>

    【讨论】:

      猜你喜欢
      • 2020-05-06
      • 2021-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-12
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      相关资源
      最近更新 更多