限制gridview表中的复选框检查

时间:2013-11-24 16:02:38

标签: jquery html asp.net gridview checkbox

我正在尝试向用户显示比较按钮,以比较asp.net中的选定行。这是我到目前为止所尝试过的。

$(function () {
    $("#myTable").find("input:checkbox").click(function () {
        var bol = $("#myTable").find("input:checkbox:checked");
        alert(bol.length);
        if (bol.length <= 3) {
            $('#hello').fadeIn();
        } else if (bol.length > 1) {
            alert('hi');
            $('#error').hide();
        } else if (bol.length >= 4) {
            $("#myTable").find("input:checkbox").not(":checked").attr("disabled", bol);
        } else {
            $('#hello').hide();
        }
    });
    $('#compare').click(function () {
        var ck = $("#myTable").find("input:checkbox:checked");
        if (ck.length === 1) {
            $('#error').show();
        } else if (ck.length > 1) {
            $('#error').hide();
        }
    });
});

现在,如果用户勾选了多个现在没有发生的复选框,我想要隐藏#error ID。

Fiddle

我也试过这个,但是如果我们选中任意4个复选框然后取消选中任何一个复选框,它就不会启用复选框。

$(function () {
    $("#myTable").find("input:checkbox").click(function () {
        var bol = $("#myTable").find("input:checkbox:checked");
        if (bol.length <= 3) {
            $('#error').hide();
            $('#hello').fadeIn();
        } else if (bol.length >= 4) {
            $("#myTable").find("input:checkbox")
                .not(":checked").attr("disabled", bol);
        } else {
            $('#hello').hide();
        }
    });
    $('#compare').click(function () {
        var ck = $("#myTable").find("input:checkbox:checked");
        if (ck.length === 1) {
            $('#error').show();
        }
    });
});

Fiddle

1 个答案:

答案 0 :(得分:0)

我能够解决这个问题。这是解决方案。回答我的问题,因为它可能对某人有帮助。

$(function () {
    // Just pass the gridview id or class name where it has checkbox in header as well as in each row. Also, define num to restrict maximum number of checkboxes, that needed to be checked.
    var grd = $('.mGrid');
    var num = 4;
    var count = 0;
    var headChk = grd.find('th>input:checkbox');
    var checks = grd.find('td>input:checkbox');
    $(headChk).change(function () {
        if ($(headChk).is(':checked')) {
            for (i = 0; i < num; i++) {
                $(checks[i]).prop("checked", true);
            }
        } else {
            $(checks).prop("checked", false);
        }
    });
    // to check or uncheck top selector
    $(checks).change(function () {
        var bol = grd.find("td>input:checkbox:checked");
        var b = grd.find("td>input:checkbox");
        var a = bol.length;
        var c = (b.length);
        if (a > num) {
            alert("Can't select more than " + num + " items");
            $(this).prop("checked", false);
        } else if (a == num) {
            $(headChk).prop("checked", true);
        } else {
            $(headChk).prop("checked", false);
        }
    });
});

Fiddle