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); // 获取选中的值
}
}
}