如何获取动态生成的表td输入值

时间:2018-11-03 14:31:39

标签: javascript html

我有一个动态生成的表格,如下所示

enter image description here

这是生成此表的代码

function pullInventory(data) {

    var container = document.getElementById('inventoryContainer')
 
    var index = 0;
 
 
    console.log(index)
    data.forEach(function(awardsSnap) {
        index ++;
         // console.log(awardsSnap, index)
        var awardItem = awardsSnap.val()

        // Attach an asynchronous callback to rea

        var NSNcard = `
        
                <tr>
                    <td class="serial">${awardItem.NSN}</td>
               
                    <td> ${awardItem.Nomenclature} </td>
                    <td>   ${awardItem.Awarddate} </td> 
                    <td> ${awardItem.Awardid} </td>
                    <td> 
                        <input type="text" placeholder="i.e. 100 EA" class="form-control" value="" id="qty${index}"style="width: 110px;">

                     </td>
                    <td> 
                        <input type="text" placeholder="i.e. $9.23 " class="form-control" value="" style="width: 110px;">
                    </td> 
                   
                </tr>

                    `;
        container.innerHTML += NSNcard;
 
    });

}

我要在按钮上单击以获取所有用户输入的数量和价格,所以我可以使用

document.querySelector("#savebtn").addEventListener("click", e => {

    var rows = document.getElementById("WelcomeTable").getElementsByTagName("tbody")[0].getElementsByTagName("tr").length;
   saveInventory(rows);
});

function saveInventory(rows) {
  const columnHeader = Array.prototype.map.call(
    document.querySelectorAll(".table th"),
    th => {
      return th.innerHTML;
    }
  );

  const tableContent = Object.values(
    document.querySelectorAll(".table tbody tr")
  ).map(tr => {
    const tableRow = Object.values(tr.querySelectorAll("td")).reduce(
      (accum, curr, i) => {
        const obj = { ...accum };
        obj[columnHeader[i]] = curr.innerHTML.trim();
 
            console.log(accum, curr, i)

        return obj;
      },
      {}
    );
    return tableRow;
  });
  

}

一切正常,除了上表中的两个输入列不检测用户输入。我无法获得输入的数量和价格值。

   Award Date: "08-23-2012"

   Award#: "SP452013D0055"

   NSN: "S222V00004789"

   Nomenclature: " BATTERIES, NICKEL-CADMIUM"

   Quantity: "<input type="text" placeholder="i.e. 100 EA" class="form-control" value="" id="qty18" style="width: 110px;">"

   Unit-Price: "<input type="text" placeholder="i.e. $9.23 " class="form-control" value="" style="width: 110px;">"

我尝试了这种方法和其他方法,但是它们输出未定义

obj [columnHeader [4]] = curr.val(); obj [columnHeader [4]] = curr.value;

如何从动态表格中获取确定的数量和价格?

3 个答案:

答案 0 :(得分:1)

val()是jQuery方法。您需要在JavaScript中使用.value

答案 1 :(得分:1)

您可以尝试执行以下操作:

window.onload = ()=>{
  let targetTable = document.getElementById('target-table');
  let targetTableRows = targetTable.rows;
  let tableHeaders = targetTableRows[0];
  
  // start from the second row as the first one only contains the table's headers
  for(let i = 1; i < targetTableRows.length; i++){
    // loop over the contents of each row
    for(let j = 0; j < targetTableRows[i].cells.length; j++){
      // something we could use to identify a given item
      let currColumn = tableHeaders.cells[j].innerHTML;
      // the current <td> element
      let currData = targetTableRows[i].cells[j];
      // the input field in the row
      let currDataInput = currData.querySelector('input');
      
      // is the current <td> element containing an input field? print its value.
      // Otherwise, print whatever is insside
      currDataInput ? console.log(`${currColumn}: ${currDataInput.value}`) 
        : console.log(`${currColumn}: ${currData.innerHTML}`); 
    }
  }
  
};
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<table class="table" id="target-table">
  <thead>
    <tr>
      <th scope="col">Person #</th>
      <th scope="col">First</th>
      <th scope="col">Last</th>
      <th scope="col">Handle</th>
      <th scope="col">Quantity</th>
      <th scope="col">Price</th>      
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">1</th>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
      <td><input type="text" value="01-quantity" id="value-01"></td>
      <td><input type="text" value="01-price" id="value-01-2"></td>      
    </tr>
    <tr>
      <th scope="row">2</th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
      <td><input type="text" value="02-quantity" id="value-02"></td>
      <td><input type="text" value="02-price" id="value-02-2"></td>      
    </tr>
    <tr>
      <th scope="row">3</th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
      <td><input type="text" value="03-quantity" id="value-03"></td>
      <td><input type="text" value="03-price" id="value-03-2"></td>     
    </tr>
  </tbody>
</table>

在上面的示例中完成的操作也应适用于您的特定情况。

另外,这是working exmaple:)

答案 2 :(得分:0)

obj [columnHeader [i]] = curr.innerHTML.trim();

innerHtml.trim仅返回其中具有文本的直接子代的标记。在您的代码中,最后两个td有一个输入作为子代。 因此,在这种情况下,您需要检查“有孩子”的“ curr”。如果有一个子项,并且输入了其tagName,则必须使用子项值。

例如

obj[columnHeader[i]] = curr.children.length && curr.children[0].tagName=="INPUT" ? curr.children[0].value : curr.innerHTML.trim();

可以将上述条件检查并分配给变量,然后再分配给键