【问题标题】:how to get dynamically generated table td input value如何获取动态生成的表 td 输入值
【发布时间】:2018-11-04 02:21:31
【问题描述】:

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

这是生成此表的代码

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;">"

我试过这个和其他的东西,但他们输出 undefine

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

我如何从动态表中获取输入的数量和价格?

【问题讨论】:

  • 请编辑您的问题并创建一个实际运行的 sn-p,显示 minimal reproducible example
  • 你将什么样的对象传递给 pullInventory?

标签: javascript html


【解决方案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】:

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

【讨论】:

  • 不仅如此,数据似乎是一个数组——如果它不是输入数组,那么 .value 也将不起作用,除非对象具有 ["value"] 属性
【解决方案3】:

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();

可以在变量赋值给键之前检查并赋值给变量

【讨论】:

  • 它仍然为两个输入字段返回 undefine
  • 你可以尝试使用 obj[columnHeader[i]] = curr.children.length && curr.children[0].tagName=="INPUT" 吗? curr.children[0].value : curr.innerHTML.trim();
猜你喜欢
  • 1970-01-01
  • 2018-08-23
  • 2014-11-04
  • 2013-12-04
  • 1970-01-01
  • 1970-01-01
  • 2012-09-06
  • 1970-01-01
  • 2013-07-30
相关资源
最近更新 更多