jQuery:同时检查/取消选中两个不同表中的复选框

时间:2015-02-10 10:34:01

标签: javascript jquery

我为表单使用动态生成的行,并且我试图同时检查/取消选中两个不同表中的复选框。 我们说如果用户点击#Table1的第一行,应该在#Table1和#Table2的第一行选中复选框。这很好用。 但是,当用户尝试取消选中相同的复选框时,没有任何反应。 任何人都可以帮我解决这个问题吗?

这是我的代码:

$('#table1').on('click', 'tr', function (event) {
    var rowIdx = $(this).closest("tr").index();
    RowSelect($("#table1"), rowIdx);
    RowSelect($("#table2"), rowIdx);
    if (event.target.type !== 'checkbox') {
        $('.checkbox', this).trigger('click');
    }
    $("input[name='RemoveRowCheckbox']").change(function (event) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').addClass("CheckedRowColor");
        } else {
            $(this).closest('tr').removeClass("CheckedRowColor");
        }
    });
});

这里jsfiddle

1 个答案:

答案 0 :(得分:0)

您正在调用RowSelect函数两次(即表1和表2),并且设置复选框始终为true。实际上对于表1,您不必再次设置复选框,因为您已经单击它。您只需要在table2中设置复选框,因此删除对Rowselect的第一次调用

//RowSelect($("#table1"), rowIdx);

现在在RowSelect函数中,你需要设置带有先前值的否定的复选框值,如下所示

function RowSelect(table, rowIdx) {
    var $chk = table.find("tr").eq(rowIdx).find("input[type=checkbox]");
    $chk.prop('checked', !$chk.is(':checked'));
};

<强> JSFiddle Demo