【问题标题】:Check boxes values returned and added to string复选框值返回并添加到字符串
【发布时间】:2020-12-16 22:04:13
【问题描述】:

我正在尝试在表格中选择一行复选框,并且对于表格中的每个 TD,它需要检查复选框是否已打勾,是否为 1,否则为 0。 我需要一个 for 循环,我将能够在每个 td 上循环,确定它是否被检查,如果是,则将 1 添加到二进制字符串或将 0 添加到二进制字符串。

这应该以每个 tr 都有自己唯一的二进制字符串结束,这些字符串来自已选中或未选中的复选框。我还想为每个 tr 设置自己的唯一 ID。

下面的代码是我目前所拥有的,但我假设我走错了方向。

任何帮助表示赞赏。谢谢

[ { ID: 000, binary: 0101010101 }  ]
function generate(){


$("#actionTable>tbody").children("tr").each(function(i, rowitem){
    $(rowitem).children("td").each(function(index, item){
        if (index == 0){
            var amid = $(item).data("amid");
        }

        else {
            //Handle checkbox
            var checked = $(item.firstChild).prop('checked')
        }
    });
});

}

【问题讨论】:

  • 几个问题...你能edit澄清这个问题吗? (1) 这个问题被标记为datatables - 你实际上是在使用DataTables,还是这只是一个标准的HTML表格? (2) 我假设你有一个复选框的初始状态 - 它是如何提供的?

标签: javascript jquery checkbox datatables binary-string


【解决方案1】:

您可以为此使用嵌套的 map()。外部映射迭代行

内部映射迭代每个输入的checked 属性,转换为数字,然后转换为字符串,然后加入数组以获得最终字符串。

我不知道 html 是什么样的,所以暂时只使用每行的行索引

const res = $('tr').map((i, el) => {

  const binary = $(el).find(':checkbox').map((_, inp) => {
      return `${+inp.checked}`;
  }).get().join('');
  
  return { index: i, binary};
  
}).get()

console.log(res)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td><input type="checkbox"></td>
    <td><input type="checkbox" checked></td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox"></td>
  </tr>
  <tr>
    <td><input type="checkbox" checked></td>
    <td><input type="checkbox"></td>
    <td><input type="checkbox" checked></td>
    <td><input type="checkbox"></td>
  </tr>
</table>

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2016-03-25
    • 1970-01-01
    相关资源
    最近更新 更多