1

我想在选中“全选”复选框时选中所有复选框,反之亦然,如果我一一选中所有复选框,则应自动选中“全选”复选框。如果我取消选中它的任何子复选框,那么“全选”复选框也应该被取消选中。

在我的代码中,所有的东西都在工作,除了一件事, 如果我一个一个地选择所有的复选框,那么“Selectall”复选框应该被自动选中。任何人都可以帮助我使这件事对我有用。供您参考,我在这里提供我的文件代码(HTML 和 Javascript 代码),以便您可以在本地机器上进行测试。:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function () {
    $("#ckbCheckAll").click(function () {
        $(".checkBoxClass").prop('checked', $(this).prop('checked'));
    });

    $(".checkBoxClass").change(function(){
        if (!$(this).prop("checked")){
            $("#ckbCheckAll").prop("checked",false);
        }
    });
});
</script>
</head>
<body>
<input type="checkbox" id="ckbCheckAll" /> Check All
    <p id="checkBoxes">
        <input type="checkbox" class="checkBoxClass" id="Checkbox1" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox2" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox3" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox4" />
        <br />
        <input type="checkbox" class="checkBoxClass" id="Checkbox5" />
        <br />
    </p>
</body>
</html>
4

4 回答 4

3

您可以检查有多少复选框以及检查了多少:

$(".checkBoxClass").change(function(){
    var all = $('.checkBoxClass');
    if (all.length === all.filter(':checked').length) {
        $("#ckbCheckAll").prop("checked", true);
    } else {
        $("#ckbCheckAll").prop("checked", false);
    }
});

不确定是否all可以$(this);

于 2013-08-23T09:38:09.560 回答
1

除了 selectAll 复选框之外,我还尝试添加 selectRow 和 selectCol 复选框,以便为复选框网格的每一行和每一列获得相同的效果。

在此处输入图像描述http://jsfiddle.net/wf_bitplan_com/snpc2L34/29/

/**
 * http://stackoverflow.com/questions/432493/how-do-you-access-the-matched-groups-in-a-javascript-regular- 
 * expression
 *  examples:
 *
 *  var matches = getRegexMatches(/(dog)/, "dog boat, cat car dog");
 *  console.log(matches);
 *
 *  var matches = getRegexMatches(/(dog|cat) (boat|car)/, "dog boat, cat car");
 *  console.log(matches);
 */
function getRegexMatches(regex, string) {
    if(!(regex instanceof RegExp)) {
        return "ERROR";
    }
    else {
        if (!regex.global) {
            // If global flag not set, create new one.
            var flags = "g";
            if (regex.ignoreCase) flags += "i";
            if (regex.multiline) flags += "m";
            if (regex.sticky) flags += "y";
            regex = RegExp(regex.source, flags);
        }
    }
    var matches = [];
    var match = regex.exec(string);
    while (match) {
        if (match.length > 2) {
            var group_matches = [];
            for (var i = 1; i < match.length; i++) {
                group_matches.push(match[i]);
            }
            matches.push(group_matches);
        }
        else {
            matches.push(match[1]);
        }
        match = regex.exec(string);
    }
    return matches;
}

/**
 * get the select_row or select_col checkboxes dependening on the selectType row/col
 */
function getSelectCheckboxes(selectType) {
  var regex=new RegExp("select_"+selectType+"_");
  var result= $('input').filter(function() {return this.id.match(regex);});
  return result;
}

/**
 * matrix selection logic 
 * the goal is to provide select all / select row x / select col x
 * checkboxes that will allow to 
 *   select all: select all grid elements 
 *   select row: select the grid elements in the given row
 *   select col: select the grid elements in the given col
 *
 *   There is a naming convention for the ids and css style classes of the the selectors and elements:
 *   select all -> id: selectall
 *   select row -> id: select_row_row e.g. select_row_2
 *   select col -> id: select_col_col e.g. select_col_3 
 *   grid element -> class checkBoxClass col_col row_row e.g. checkBoxClass row_2 col_3
 */
$(document).ready(function () {
    // handle click event for Select all check box
    $("#selectall").click(function () {
       // set the checked property of all grid elements to be the same as
       // the state of the SelectAll check box
       var state=$("#selectall").prop('checked');
       $(".checkBoxClass").prop('checked', state);
       getSelectCheckboxes('row').prop('checked', state);
       getSelectCheckboxes('col').prop('checked', state);
    });

    // handle clicks within the grid
    $(".checkBoxClass").on( "click", function() {
      // get the list of grid checkbox elements
      // all checkboxes
      var all = $('.checkBoxClass');
      // all select row check boxes
      var rows = getSelectCheckboxes('row');
      // all select columnn check boxes
      var cols = getSelectCheckboxes('col');
      // console.log("rows: "+rows.length+", cols:"+cols.length+" total: "+all.length);
      // get the total number of checkboxes in the grid
      var allLen=all.length;
      // get the number of checkboxes in the checked state
      var filterLen=all.filter(':checked').length;
      // console.log(allLen+"-"+filterLen);
      // if all checkboxes are in the checked state  
      // set the state of the selectAll checkbox to checked to be able
      // to deselect all at once, otherwise set it to unchecked to be able to select all at once
      if (allLen == filterLen) {
        $("#selectall").prop("checked", true);
      } else {
        $("#selectall").prop("checked", false);
      }

      // now check the completeness of the rows
      for (row = 0; row < rows.length; row++) {
        var rowall=$('.row_'+row);
        var rowchecked=rowall.filter(':checked');
        if (rowall.length == rowchecked.length) {
          $("#select_row_"+row).prop("checked", true);
        } else {  
          $("#select_row_"+row).prop("checked", false);
        }
     }
    });

    $('input')
      .filter(function() {
        return this.id.match(/select_row_|select_col_/);
    }).on( "click", function() {
      var matchRowColArr=getRegexMatches(/select_(row|col)_([0-9]+)/,this.id);
      var matchRowCol=matchRowColArr[0];
      // console.log(matchRowCol);
      if (matchRowCol.length==2) {
        var selectType=matchRowCol[0];  // e.g. row
        var selectIndex=matchRowCol[1]; // e.g. 2
        // console.log(this.id+" clicked to select "+selectType+" "+selectIndex);
        // e.g. .row_2
        $("."+selectType+"_"+selectIndex)
         .prop('checked', $("#select_"+selectType+"_"+selectIndex).prop('checked'));
     }
    });
  });
于 2015-06-21T05:50:15.413 回答
0

使用 jQuery(":checkbox")

也许你可以看看jquery的@selectors http://api.jquery.com/category/selectors/

于 2013-08-23T09:38:53.757 回答
0

//----------Select AllCheckBoxes Begin ------------------------
function toggleChkBox() {
  $('#tblPermissionDetails td input:checkbox').prop('checked', $('#chkSelectAll')[0].checked);
}
//----------Select AllCheckBoxes End --------------------------

//----------Check/Uncheck SelectAll checkbox based on other checkboxes Begin----------------
$('#tblPermissionDetails td input:checkbox').change(function() {
  if (!$(this).prop("checked")) {
    $("#chkSelectAll").prop("checked", false);
  } else {
    var PermissionList = [];
    var PermissionListChecked = [];
    $('#tblPermissionDetails td input:checkbox').each(function() {
      PermissionList.push(this.name);
    })
    $('#tblPermissionDetails td input:checkbox:checked').each(function() {
      PermissionListChecked.push(this.name);
    })
    if (PermissionList.length == PermissionListChecked.length) {
      $("#chkSelectAll").prop("checked", true);
    }
  }
});
//----------Check/Uncheck SelectAll checkbox based on other checkboxes End------------------
<table class="table table-striped" id="tblPermissionDetails">
  <thead>
    <tr>
      <th>Sl.No</th>
      <th>Permission</th>
      <th>Description</th>
      <th><input type="checkbox" id="chkSelectAll" onclick="toggleChkBox();" />(Select All)</th>
    </tr>
  </thead>
  <tbody>
    @{ int i = 1; List
    <FDSApp.Models.RolePermissionDetailsModel> permissionModel = Model; foreach (var item in permissionModel) {
      <tr>
        <td>@i</td>
        <td>@item.PermissionName</td>
        <td>@item.Description</td>
        <td>@Html.CheckBox(@item.PermissionId.ToString(), @item.IsEnabled == 0 ? false : true)</td>
      </tr>
      i = i + 1; } }
  </tbody>
</table>

于 2019-10-21T05:01:51.287 回答