开发者

using a button instead of a checkbox to check all checkboxes in jquery

Currently using the following to select all checkboxes when a checkbox with id #checkall is checked.

<script type="text/javascript">
$(function () {
    $('#checkall').click(function () {
        $(this).parents('fieldset:eq(0)').find(':checkbox').attr('checked', this.checked);
    });
});
</script>

How can i change this to allow 开发者_开发问答for the use of a button, instead of a checkbox? Ive tried switching them out in the html, but it doesnt seem to work.


it's this bit here

attr('checked', this.checked);

a button does not have a checked attribute

Try using element.data to hold the value of the current checked status instead

for example, set $('#checkall').data("checked","false") on page initialization, and then on subsequent calls check what that value is, and switch it out for the opposite...


Your problem is that you're still using "this.checked", a button will never be checked. You'll have to use the 'toggle' feature instead.


Is the problem maybe in your

, this.checked

I.e. buttons don't have a checked status


You still use this.checked in the attr(...) code which of course won't work as this is a button now and not a checkbox anymore. The following stores the current "checked" status in a data attribute on the button and thus allows you to toggle the checkboxes as before

$('#checkall').click(function () {
    var ele = $(this);
    var checked = ele.data("checked");
    checked = checked == undefined ? true : checked;
    $(this)
        .data("checked", !checked)
        .parents('fieldset:eq(0)')
        .find(':checkbox')
        .attr('checked', checked);
});


var checked = false;
var checkAll = $('#checkall');
var checkboxes = checkAll.parents('fieldset:eq(0)').find(':checkbox');

checkAll.click(function () {
    checkboxes.attr('checked', checked = !checked);
});

I've done two things:

  • The current state of the checkboxes is stored in the checked variable.
  • The checkboxes are not queried for on every click; instead we cache the collection and simply set the attribute when the checkAll button is clicked.

And, if you're worried about global variables, then just wrap it all in its own scope:

(function(){
    var checked = false;
    var checkAll = $('#checkall');
    var checkboxes = checkAll.parents('fieldset:eq(0)').find(':checkbox');

    checkAll.click(function () {
        checkboxes.attr('checked', checked = !checked);
    });
})();


Give each group a certain class, then do

$(".yourclass").attr("checked","true");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜