【问题标题】:how to get the ids of checked checkboxes in jquery如何在jquery中获取选中复选框的ID
【发布时间】:2021-04-27 16:17:03
【问题描述】:

我想获取选中复选框的 id 并使用 jquery 将这些 id 存储在一个数组中。 谁能给我正确的代码。

我试过了

提前致谢:)

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
        return $(this).val();
    }).toArray();
    console.log(searchIDs);
});

【问题讨论】:

  • 你可以把return $(this).val();改成this.id
  • 我知道了,但它确实返回数组
  • 它给出了逗号分隔的值。我无法循环遍历它
  • 它给出了一个 id 数组,你可以根据需要循环遍历。
  • 实际上查看源代码,toArray()get() 现在几乎相同,并且都使用对 slice() 的调用,因此在现代版本的 jQuery 中没有区别。

标签: html jquery checkbox


【解决方案1】:

使用attr() 方法获取id。像这样:

$(this).attr('id');

你需要这样的结果吗?

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
        return $(this).attr('id');
    }).toArray();
    console.log(searchIDs);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="find-table">
  <input id="1" type="checkbox">
  <input id="2" type="checkbox">
  <input id="3" type="checkbox">
</div>

<button id="merge_button">merge</button>

【讨论】:

    猜你喜欢
    • 2011-10-17
    • 1970-01-01
    • 2017-08-22
    • 1970-01-01
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 2013-09-28
    相关资源
    最近更新 更多