我如何迭代一个 table ,它在 td 中有输入标签

How to i iterate over a table which has input tags inside the td

<div id="tableDiv">
<table  id="mytable">
  <tr> 
    <td><input type="text" ></td>
    <td><input type="text" ></td>
  </tr>
  <tr>
    <td><input type="text" ></td>
    <td><input type="text" ></td>
  </tr>
</table></div>

如何遍历此 table 并将值存储在数组变量中,

将使用添加行按钮向此 table 添加额外的行,如何确定行数以及如何将值存储在变量中,以便我能够一次检索每一行的值

这将帮助您将 table 中的所有输入值存储为数组!

Html

<div id="tableDiv">
  <table id="mytable">
    <tr>
      <td><input type="text"></td>
      <td><input type="text"></td>
    </tr>
    <tr>
      <td><input type="text"></td>
      <td><input type="text"></td>
    </tr>
  </table>
</div>
<button onclick="print()">Print</button>

Js

 const tableEle = document.querySelectorAll('#mytable input')
// Creating an empty array
  let array = [];
// Function to add all values from inputs and store in array variable 
  function createArr() {
    tableEle.forEach(ele => {
      array.push(ele.value.trim())
    })
  }
// Finally this function when called creates and logs in console 
  function print() {
    createArr()
    console.log(array)
  }

我想你可以从这段代码中得到一些想法。

这是 JsFiddle -> click here

function myFunction() {
var value1 = document.getElementById("val1").value; //get first inputBox value
var value2 = document.getElementById("val2").value; //get second inputbox value
  
if(value1 !== "" && value2 !== ""){ //check input boxes are filled

  var table = document.getElementById("myTable"); //Start here creating the table
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
    
  cell1.innerHTML = value1;
  cell2.innerHTML = value2;  
  }else{
    alert("please fill all input boxes")
  }
}

function getValues(){
//search and get the value from table
  var table = document.getElementById("myTable");
  
  var findValue = document.getElementById("findVal").value;
  
  if(findValue){
 
    for (var r = 0, n = table.rows.length; r < n; r++) {
      for (var c = 0, m = table.rows[r].cells.length; c < m; c++) {
        
        if(findValue === table.rows[r].cells[c].innerHTML){
            alert("value found: "+table.rows[r].cells[c].innerHTML);
          return false
        }          
      }
    }
  }else{
    alert("please fill input boxes")
  }
}
.main{
  display:flex;
}

.btn{
   margin-left:2px;
}
.input{
   width:100px 
}
<div class="main">

  <div>
    <input class="input" type="text" id="val1" onfocus="this.value=''">
    <input class="input" type="text" id="val2" onfocus="this.value=''">
  </div>

  <div class=btn>
     <button type="button" onclick="myFunction()">Try it</button> 
  </div>
  
  <div class=btn>
      <button type="button" onclick="getValues()">find</button>
  </div>
  
  <div>
     <input class="input" type="text" id="findVal">
  </div>

</div><br>

  <div>
  
    <table id="myTable">
      <tr>
        <td></td>
        <td></td>
      </tr>
    </table>
    
  </div>