首页 > 解决方案 > 获取html表格每一行输入字段的值

问题描述

我有一个 html 表。每行都有带有隐藏边框的输入字段。当我按下一个按钮时,如果可能的话,它应该给我每个表格行的输入字段的所有值,而不使用 id 和 class。

html:

<div class="row" style="z-index:0;">
<div class="col-md-12">
    <table id="detailTable" class="table table-bordered table-sm">
        <thead class="thead-light" style="text-align:center">
            <tr>
                <th style="width:130px;">Date</th>
                <th style="width:300px;">Particulars</th>
                <th style="width:10px;">C.B.F</th>
                <th style="width:180px;">Dr. Amount</th>
                <th style="width:180px;">Cr. Amount</th>
                <th style="width:200px;">Balance</th>
                <th style="width:10px;">Opt</th>
            </tr>
        </thead>
        <tbody>
           <tr>
              <td> <input type='text' value='11-12-2018'/> </td>
              <td> <input type='text' value='Cash'/> </td>
              <td> <input type='text' value=''/> </td>
              <td> <input type='text' value='20000'/> </td>
              <td> <input type='text' value='15000'/> </td>
              <td> <input type='text' value='-5000'/> </td>
              <td> <input type='button' value='Delete'/> </td>
           </tr>
        </tbody>
    </table>
</div>
<button class='btn btn-success'>Show</div>
</div>

我试过的 JavaScript

var rowsInTable = $("#detailTable tr").length;
rowsInTable--;
row.parentNode.removeChild(row);

for(i=1;i<=rowsInTable;i++)
{
  console.log(document.getElementById("detailTable").rows[i].innerHTML);
}

标签: javascripthtml

解决方案


由于 JQuery 没有被标记,这就是我只在 Javascript 中这样做的方式:

var tableRows = document.getElementById("detailTable").rows

for (i = 1; i < tableRows.length; i++) {
  var myrow = tableRows[i];
  for (j = 0; j < myrow.cells.length; j++) {
    var mytd = myrow.cells[j];
    console.log(mytd.children[0].value);
  }
}

这是 JSFiddle 演示

您可以进一步微调它以获得格式化的输出。PS:检查控制台的输出。


推荐阅读