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

时间:2014-09-20 02:47:41

标签: jquery html checkbox

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 :(得分:0)

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

主要问题在于这一行:

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

而不是这一行应该是:

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

请参阅更新fiddler。

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

相关问题