我有以下几点:
$(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"在选中和未选中之间切换。想法吗?那不是几十行代码吗?
当前回答
你也可以这样写
$(function() {
$("#checkbox-toggle").click(function() {
$('input[type=checkbox][name=checkbox_id\\[\\]]').click();
});
});
当用户单击id为“#checkbox-toggle”的按钮时,只需要调用复选框的单击事件。
其他回答
如果你想单独切换每个框(或者只有一个框也可以):
我建议使用.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在所有浏览器中都是一样的?
在我看来,建议正常变种的人是GigolNet Gigolashvili,但我想建议更漂亮的变种。检查它
$(document).on('click', '.fieldWrapper > label', function(event) {
event.preventDefault()
var n = $( event.target ).parent().find('input:checked').length
var m = $( event.target ).parent().find('input').length
x = n==m? false:true
$( event.target ).parent().find('input').each(function (ind, el) {
// $(el).attr('checked', 'checked');
this.checked = x
})
})
最基本的例子是: //获取DOM元素 var checkbox = document.querySelector('input'), button = document.querySelector('button'); //在按钮上绑定“cilck”事件 按钮。addEventListener(“点击”,toggleCheckbox); //当单击按钮时,切换复选框 函数toggleCheckbox () { 复选框。checkbox.checked = ! }; < input type = "复选框”> < / > <按钮切换复选框按钮>
这是你想要的另一种方式。
$(document).ready(function(){
$('#checkp').toggle(
function () {
$('.check').attr('Checked','Checked');
},
function () {
$('.check').removeAttr('Checked');
}
);
});
你可以这样写:
$(document).ready(function() {
$("#select-all-teammembers").click(function() {
var checkBoxes = $("input[name=recipients\\[\\]]");
checkBoxes.prop("checked", !checkBoxes.prop("checked"));
});
});
在jQuery 1.6之前,当我们只有attr()而没有prop()时,我们习惯这样写:
checkBoxes.attr("checked", !checkBoxes.attr("checked"));
但是prop()在应用于“布尔”HTML属性时具有比attr()更好的语义,所以在这种情况下通常是首选。