Javascript 如何获取多个选定复选框
我想获取多个选中复选框的id HTML:Javascript 如何获取多个选定复选框,javascript,jquery,html,checkbox,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" i
<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">
或
$("body").on("click", "#button", function(){
var ids = $(':checkbox:checked.a')
.map(function() {
return this.id;
}).toArray();
console.log(ids); // an array of ids
});
$("body").on("click", "#button", function(){
var ids = $(':checkbox.a')
.map(function() {
if( this.checked )
return this.id;
}).toArray();
console.log(ids); // an array of ids
});
或
$("body").on("click", "#button", function(){
var ids = $(':checkbox:checked.a')
.map(function() {
return this.id;
}).toArray();
console.log(ids); // an array of ids
});
$("body").on("click", "#button", function(){
var ids = $(':checkbox.a')
.map(function() {
if( this.checked )
return this.id;
}).toArray();
console.log(ids); // an array of ids
});
要获取选中对象的
id
:
$("#button").live('click',function(){
var a = document.getElementsByClassName("a");
alert(a);
alert(a.checked);
});
$('.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.
请注意,根据w3c规范,以数字开头的id无效强>
ID和名称标记必须以字母([a-Za-z])开头,后面可以是任意数量的字母、数字([0-9])、连字符(“-”)、下划线(“)、冒号(:”)和句点(“.”)
要选中复选框:
除非jQuery版本<1.4.4,否则不要使用live
$("#containerId").on('click','#button', function(){
$('.a').prop('checked', true);
});
我不知道为什么每个人都会发布代码来检查复选框 我想获取多个选中复选框的id 为此,请使用以下代码:
$("#button").click(function() {
var selected = $(".a:checked").map(function() {
return this.id;
}).get();
alert(selected.join(","));
});
您也不应该使用live()
delegate()
或on()
是更好的解决方案,但只有在页面加载后将#按钮
元素添加到页面时才需要它们。尝试以下代码:
$("#button").live('click',function(){
$("input:checkbox").each(function()
{
if($(this).is(':checked')){
alert( $(this).attr('id') )
}
});
});
我希望它能帮助你我读了问题,然后是第一个答案,当我在里面看到
直播时,我想我被它淹没了<代码>:)
请,$(this).is(':checked')
=>this.checked
。这里的最后一件事是如何返回id的?