获取嵌套在表中的输入值

时间:2018-10-13 23:06:37

标签: javascript html html-table

我有一个表格,其中每行在一个单元格中的div内嵌套两个按钮和一个输入。我必须能够过滤出输入不是整数的行。该代码一直有效,直到我添加了标有星号的4行(两个按钮)。

<table id='myTable'>
{% for x in data %}
<tr>
<td style='max-width:175px;'>
  *<div style='display:-webkit-flex;display:flex;flex-wrap:nowrap;'>
    *<button name='plusminus' type="button" class="sub" style='display:none;'>-</button>
    <input type="text" class="form-control txtBox" style=max-width:90px; name="{{ x[2] }}" pattern="[0-9]{0,5}" title="Use only whole numbers. Eg 3 NOT 3.2" placeholder='Order...'>
    *<button name='plusminus' type="button" class="add" style='display:none;'>+</button>
  *</div>
</td>
</tr>
{% endfor %}
</table>

(我认为)问题出在下面的“ firstElementChild”和“ firstChild”上,因为删除了上面的星号行后,代码工作正常,表明问题出在我的函数指向错误的元素。

<script>
function displayorderguide() {
   var tbl = document.getElementById('myTable'),
      rows = tbl.tBodies[0].children, l = rows.length, i,
      filter = function(cells) {
   var values = [
      parseInt(cells[0].firstChild.nodeValue.replace(/,/g,''),10),
      parseFloat(cells[{{parprofiles|length}}+2].firstElementChild.value.replace(/,/g,''))
                 ];
   if( Number.isInteger(+values[1]) ) return true;
                                      return false;
                              };
    for( i=0; i<l; i++) {
         if( !filter(rows[i].cells)) rows[i].style.display = "";
                   }
        }
</script>

我的猜测是,我需要查看第一个获取div,然后查看第二个获取输入(在我需要第一个获取输入之前)。

我尝试将'firstElementChild'替换为'.children[0].children[1]',但这似乎不起作用。

所以我的问题是,既然嵌套在div内,那么如何解析多级html以获取该输入呢?

1 个答案:

答案 0 :(得分:0)

根据您提供的HTML,

document.querySelectorAll('input.txtBox')应该可以正常工作。通常,firstElementChildchildren之类的东西是在您没有ID的类时使用的。

在您的方案中,您可以这样应用它:

const rows = document.querySelectorAll('#myTable tr');
document.querySelectorAll('input.txtBox').forEach((input, i) => {
    if (!Number.isInteger(Number(input.value))) rows[i].style.display = 'none';
});

简而言之:

  1. 获取所有行。
  2. 获取所有输入并对其进行迭代。
  3. 如果输入的值不是整数,则将display="none";应用于关联的行。
相关问题