我有以下几点:
$(document).ready(function()
{
$("#select-all-teammembers").click(function() {
$("input[name=recipients\\[\\]]").attr('checked', true);
});
});
我希望id="select-all-teammembers"在选中和未选中之间切换。想法吗?那不是几十行代码吗?
我有以下几点:
$(document).ready(function()
{
$("#select-all-teammembers").click(function() {
$("input[name=recipients\\[\\]]").attr('checked', true);
});
});
我希望id="select-all-teammembers"在选中和未选中之间切换。想法吗?那不是几十行代码吗?
当前回答
如果你想单独切换每个框(或者只有一个框也可以):
我建议使用.each(),因为如果你想要发生不同的事情,它很容易修改,而且仍然相对简短且易于阅读。
例如:
// toggle all checkboxes, not all at once but toggle each one for its own checked state:
$('input[type="checkbox"]').each(function(){ this.checked = ! this.checked });
// check al even boxes, uncheck all odd boxes:
$('input[type="checkbox"]').each(function(i,cb){ cb.checked = (i%2 == 0); });
// set all to checked = x and only trigger change if it actually changed:
x = true;
$('input[type="checkbox"]').each(function(){
if(this.checked != x){ this.checked = x; $(this).change();}
});
顺便说一句…… 不知道为什么每个人都使用.attr()或.prop()来(un)检查东西。
据我所知,是元素。Checked在所有浏览器中都是一样的?
其他回答
这是你想要的另一种方式。
$(document).ready(function(){
$('#checkp').toggle(
function () {
$('.check').attr('Checked','Checked');
},
function () {
$('.check').removeAttr('Checked');
}
);
});
从jQuery 1.6开始,你可以使用.prop(function)来切换每个找到的元素的检查状态:
$("input[name=recipients\\[\\]]").prop('checked', function(_, checked) {
return !checked;
});
这个很适合我。
$("#checkall").click(function() {
var fruits = $("input[name=fruits\\[\\]]");
fruits.prop("checked", $(this).prop("checked"));
});
//this toggles the checkbox, and fires its event if it has
$('input[type=checkbox]').trigger('click');
//or
$('input[type=checkbox]').click();
您还可以通过执行以下操作来切换复选框。目前使用引导切换复选框。
<link href='https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css' rel='stylesheet'>
<script src='https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js'></script>
<input type='checkbox' id='toggleScheduler' name='toggleScheduler' data-toggle='toggle' data-on='Enabled' data-off='Disabled'
$("#toggleScheduler").bootstrapToggle('on'); // enable toggle checkbox
$("#toggleScheduler").bootstrapToggle('off'); // disable toggle checkbox