Home > Web Front-end > JS Tutorial > body text

The ultimate solution to select all CheckBox in javascript_javascript skills

WBOY
Release: 2016-05-16 15:58:16
Original
1455 people have browsed it

In our program development, we often use CheckBox to select all, usually in some data-bound controls such as Gridview, etc.

The following takes Repeater as an example, and puts the CheckBox control in the header and item of Repeater.

<asp:Repeater ID="rptGroup" runat="server"> 
  <HeaderTemplate> 
    <table width="100%" cellspacing="1" >
      <tr> 
        <td width="3%" align="center" >
         <input type="checkbox" id="chkAll" name="chkAll" value="checkbox" 
         onclick="checkAll  ('chkAll',this);" />             
        </td> 
      </tr> 
  </HeaderTemplate> 
  <ItemTemplate> 
    <tr> 
    <td align="center" >
     <input type="checkbox" name="chkSelect" value='<%# Eval("ID") %>' 
     onclick="checkAll('chkAll',this);"/>
    </td> 
    </tr> 
  </ItemTemplate> 
  <FooterTemplate> 
    </table> 
  </FooterTemplate> 
 </asp:Repeater> 
Copy after login

The following is the js script

The checkAll method implements all selection and deselection of CheckBox.

function checkAll(chkAllID, thisObj) {
  var chkAll = document.getElementById(chkAllID);
  var chks = document.getElementsByTagName("input");
  var chkNo = 0;
  var selectNo = 0;
  for (var i = 0; i < chks.length; i++) {
    if (chks[i].type == "checkbox") {
      //全选触发事件  
      if (chkAll == thisObj) {
        chks[i].checked = thisObj.checked;
      }
      //非全选触发 
      else {
        if (chks[i].checked && chks[i].id != chkAllID)
          selectNo++;
      }
      if (chks[i].id != chkAllID) {
        chkNo++;
      }
    }
  }
  if (chkAll != thisObj) {
    chkAll.checked = chkNo == selectNo;
  }
} 
Copy after login

The checkSelectNo function is used to obtain the number of selected checkboxes. This is very useful when used to determine whether there is a checkbox.

function checkSelectNo(chkAllID) {
  var chks = document.getElementsByTagName("input");
  var selectNo = 0;
  for (var i = 0; i < chks.length; i++) {
    if (chks[i].type == "checkbox") {
      if (chks[i].id != chkAllID && chks[i].checked) {
        selectNo++;
      }
    }
  }
  return selectNo;
} 
Copy after login

The above is the entire content of this article, I hope you all like it.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template