码迷,mamicode.com
首页 > 其他好文 > 详细

多选,全选,反选

时间:2020-01-23 21:14:16      阅读:84      评论:0      收藏:0      [点我收藏+]

标签:log   nts   for   push   body   on()   res   false   nbsp   

js实现复选框的多选,全选,反选

 

<table>

 <thead>

  <tr>

   <th><input type="checkbox" name="chkAllResourceType" id="chkAllResourceType" onclick="selectAll()">全选</th>

   <th>测试一</th>

   <th>测试二</th>

   <th>测试三</th>

   <th>测试四</th>

  </tr>

 </thead>

 <tbody>

  <tr>

   <td><input type="checkbox" name="resourceType" id="resourceType" value="1" ></td>

   <td>1</td>

   <td>2</td>

   <td>3</td>

   <td>4</td>

  </tr>

  <tr>

   <td><input type="checkbox" name="resourceType" id="resourceType" value="2" ></td>

   <td>1</td>

   <td>2</td>

   <td>3</td>

   <td>4</td>

  </tr>

  <tr>

   <td><input type="checkbox" name="resourceType" id="resourceType" value="3" ></td>

   <td>1</td>

   <td>2</td>

   <td>3</td>

   <td>4</td>

  </tr>

  <tr>

   <td><input type="checkbox" name="resourceType" id="resourceType" value="4" ></td>

   <td>1</td>

   <td>2</td>

   <td>3</td>

   <td>4</td>

  </tr>

 </tbody>

</table>

 

/* 多选 全选 反选 */

var thEle = document.getElementById("chkAllResourceType");

var selEle = document.getElementsByName("resourceType");

var checkboxSelect = []; // 存放选中数据 

var tmp = 0;

// 表格全选,反选

function selectAll() {

 if(thEle.checked == true) {

  checkboxSelect = [];

  for(var i = 0; i < selEle.length; i++) {

   selEle[i].checked = true;

  }

 } else {

  checkboxSelect = [];

  for(var i = 0; i < selEle.length; i++) {

   selEle[i].checked = false;

  }

  tmp=0;

 }

}

 

// 表格多选

for(var i = 0; i < selEle.length; i++) {

 selEle[i].onclick = function() {

  if(this.checked == true) {

   console.log("选中为: "+this);

   tmp++;

  } else {

   tmp--;

  }

  if(tmp == selEle.length) {

   thEle.checked = true;

  } else {

   thEle.checked = false;

  }

 }

 

// 获取表格中,选中的值id

function checkedValues() {

 checkboxSelect = [];

 var arr = new Array();

 var temp = document.getElementsByName(‘resourceType‘);

 for (var i = 0; i < temp.length; i++) {

  if (temp[i].checked == true) {

   arr.push(temp[i].value);

   checkboxSelect.push(selEle[i].value); // 获取选中的值

  }

 } 

}

多选,全选,反选

标签:log   nts   for   push   body   on()   res   false   nbsp   

原文地址:https://www.cnblogs.com/tongguilin/p/12231153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!