javascript - 如何获得多个选中的复选框

标签 javascript jquery html checkbox

我想获取选中的多个复选框的id

HTML:

<input type="checkbox" class="a" id="1">1
<input type="checkbox" class="a" id="2">2
<input type="checkbox" class="a" id="3">3
<input type="checkbox" class="a" id="4">4
<input type="checkbox" class="a" id="5">5

<input type="button" value="Button" id="button">

JS:

$("#button").live('click',function(){
    var a = document.getElementsByClassName("a");
    alert(a);
    alert(a.checked);
});

JS Fiddle

最佳答案

获取选中的id:

$('.a').filter(function(){
    return this.checked // Takes only checked checkboxes.
}).map(function(){
    return this.id // Makes an array which its elements are the ids.
}).get(); // Returns the array.

Live DEMO

请注意,根据 w3c 规范,以数字开头的 ID 无效!

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

检查复选框:

除非你的 jQuery 版本是 <1.4.4

,否则不要使用 live
$("#containerId").on('click','#button', function(){
  $('.a').prop('checked', true);
});

Live DEMO

关于javascript - 如何获得多个选中的复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10795947/

相关文章:

html - 用超出限制的文本填充框

javascript - 用 <br> 替换\n 无效

javascript - 隐藏重复的列表项/具有相同内容的列表项

javascript - 以某种方式禁用/删除悬停对页面加载的影响,启用点击事件

javascript - 下拉 onchange 函数调用不起作用

javascript - Angular2-在标题和侧边栏组件之间传递标志状态

javascript - 检测 Bootstrap 模式以更改按键输入的目的地

javascript获取数据属性,使用循环不起作用

javascript - 如何在需要的字段集标签中制作输入标签?

javascript - Object.getPrototypeOf(o) 方法问题