简体   繁体   English

从表中选中的复选框中获取所有 id 值

[英]Get all id values from checked checkbox in table

<table id="tab" border='1' style='width:100%'>
        <tr ><td>'hi'</td><td><input type='checkbox' id='1'/></td></tr>
        <tr><td>'hi'</td><td><input type='checkbox' id='2' /></td></tr>
        <tr ><td>'hi'</td><td><input type='checkbox'id='3' /></td></tr>
        <tr ><td>'hi'</td><td><input type='checkbox'id='4' /></td></tr>
</table>

this is example code, i need to return list of if that are checked, so if i check all of them i get lit[1,2,3,4] if i select only fist 2 list[1,2] and so on.这是示例代码,我需要返回是否已检查的列表,所以如果我检查所有这些,我会得到 lit[1,2,3,4] 如果我 select 只有拳头 2 列表 [1,2] 等等. Please help me!请帮我!

Try this:尝试这个:

var list=[]
$("#tab :checked").each(function(i,e){
  list.push($(this).attr("id"))
})

Find all the checkbox elements and filter those which are checked.找到所有的复选框元素并过滤那些被选中的元素。

 const checkedCheckboxes = Array.from(document.querySelectorAll('input[type=checkbox]')).filter(checkbox => checkbox.checked) console.log(checkedCheckboxes)
 <table id="tab" border='1' style='width:100%'> <tr> <td>'hi'</td> <td><input type='checkbox' id='1' /></td> </tr> <tr> <td>'hi'</td> <td><input type='checkbox' id='2' /></td> </tr> <tr> <td>'hi'</td> <td><input type='checkbox' id='3' /></td> </tr> <tr> <td>'hi'</td> <td><input type='checkbox' id='4' /></td> </tr> </table>

You should be assigning a value to each checkbox instead.您应该为每个复选框分配一个值。 Please do not use the ID attribute to store data.请不要使用 ID 属性来存储数据。

When you are ready to grab the IDs, reference the value of the field.当您准备好获取 ID 时,请引用该字段的值。

 document.querySelector('.btn-disp').addEventListener('click', e => { const ids = [...document.getElementById('tab').querySelectorAll('td input[type="checkbox"]:checked')].map(cb => cb.value); console.log(`Selected IDs: ${ids.join(', ')}`); });
 body { font-size: 0.75em; } table { width: 100%; } table, td { border: thin solid black; border-collapse: collapse; } td { padding: 0.25em; }.as-console-wrapper { max-height: 2em;important; }
 <table id="tab"> <tr> <td>Item #1</td> <td><input type="checkbox" value="1" /></td> </tr> <tr> <td>Item #2</td> <td><input type="checkbox" value="2" /></td> </tr> <tr> <td>Item #3</td> <td><input type="checkbox" value="3" /></td> </tr> <tr> <td>Item #4</td> <td><input type="checkbox" value="4" /></td> </tr> </table> <br /> <button class="btn-disp">Display Selected IDs</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM