1. 程式人生 > >js實現複選框的多選,全選,反選

js實現複選框的多選,全選,反選

多選,全選,反選

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