首页 文章

jQuery选中所有复选框,如果已选中复选框,则不要.change()

提问于
浏览
0

JSFIDDLE

当您选中其中一个框时,相应的表格单元格会删除其文本并将其放在输入文本值中 . 问题在于select all函数,因为它不会正确触发.change()事件 . 如果选中一个框,然后选中“全选”复选框,则会清除单元格值 . 如何确定是否已经检查过,不执行.change()函数?

$("#selectall").click(function () {
var checkall = $("#selectall").prop('checked');

if (checkall) {

    $('#amazon-update :checkbox').each(function () {
        var $this = $(this);

        if ($this.is(':checked')) {
            //nothing
        } else {
            $(".checkbox").prop("checked", true).change();
        }
    });

} else {

    $('#amazon-update :checkbox').each(function () {
        var $this = $(this);

        if ($this.is(':checked')) {
            $(".checkbox").prop("checked", false).change();
        } else {
            //nothing                           
        }
    });
}
});

$(".checkbox").click(function () {

if ($(".checkbox").length == $(".checkbox:checked").length) {
    $("#selectall").prop("checked", true);

} else {
    $("#selectall").prop("checked", false);
}
});

$('#amazon-update :checkbox').change(function () {

var $this = $(this);

// $this will contain a reference to the checkbox

if ($this.is(':checked')) {

    // the checkbox was checked
    var sku_td = $this.parent().siblings('.sku').text();
    var price_td = $this.parent().siblings('.price').text();
    var quantity_td = $this.parent().siblings('.quantity').text();

    $this.parent().siblings('.price').empty();
    $this.parent().siblings('.quantity').empty();

    var sku = $('<input type="hidden" name="sku[]" value="' + sku_td + '">');
    var price = $('<input type="text" class="form-control" name="price[]" value="' + price_td + '">');
    var quantity = $('<input type="text" class="form-control" name="quantity[]" value="' + quantity_td + '">');

    $this.parent().siblings('.sku').append(sku);
    $this.parent().siblings('.price').append(price);
    $this.parent().siblings('.quantity').append(quantity);
} else {

    // the checkbox was unchecked           
    var sku_td = $this.parent().siblings('.sku').children().val();
    var price_td = $this.parent().siblings('.price').children().val();
    var quantity_td = $this.parent().siblings('.quantity').children().val();

    $this.parent().siblings('.sku').empty();
    $this.parent().siblings('.price').empty();
    $this.parent().siblings('.quantity').empty();

    $this.parent().siblings('.sku').append(sku_td);
    $this.parent().siblings('.price').append(price_td);
    $this.parent().siblings('.quantity').append(quantity_td);

}

});

1 回答

  • 0

    我在小提琴上为你更新了代码 .

    主要问题是这一行:

    $(".checkbox").prop("checked", true).change();
    

    它应该是:而不是这一行

    $ this.prop(“checked”,true).change() .

    请参考更新fiddler .

    http://jsfiddle.net/5msp5jbn/6/

相关问题