简体   繁体   English

如何获取表中的输入值?

[英]How to get the input value in a table?

I have a table with dynamic rows that each rows contain an input alongside of its button(in the third cell). 我有一个带有动态行的表,每行在它的按钮旁边(在第三个单元格中)都包含一个输入。

The code below represents one row of my table: 下面的代码代表表的一行:

 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> 

As you see the console.log() shows the content of cells except the third cell. 如您所见, console.log()显示除第三个单元格以外的单元格内容。 The other questions did not help me (like: How to retrieve value of input type in a dynamic table ) 其他问题对我没有帮助(例如: 如何在动态表中检索输入类型的值

How can I access the input value in the third cell? 如何访问第三个单元格中的输入值?

Based on your HTML code, row.cells[2].children[0].value gets the value of the div , not the input . 根据您的HTML代码, row.cells[2].children[0].value获取div的值,而不是input To get the value of the input , you can use: 要获取input的值,可以使用:

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

Code: 码:

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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