1. 程式人生 > >checkbox單選 全選例項

checkbox單選 全選例項

單選框就是改變checked屬性的值 當checked值為false 點選後值改為true 反之一樣 當單選框都選中的時候就是通過判斷checked為true的個數跟checkbox的長度是否一致 當checked為true的個數跟checkbox的長度一致的時候就會將全選框checked值改為true 否則為false 即

var count = $("input[name='id']:checkbox:checked").length;
			if (count == $("input[name='id']:checkbox").length) {
				$("input[name=allselect]:checkbox").prop("checked", true);
			}

完整示例

	str += '<td  style="text-align:right; padding-right:0px;"><input type="checkbox" name="id" value='+ datalist[i].id+ ' onclick="userCheck(this)" ></td><td style="width:5%;texalign:left;">'+ datalist[i].id+ '</td>
str += '<div style="width:180px; height:25px;margin-top:10px;"><div style="width:49px; float: left;clear:right;"><input style="float: right; margin-top:10px;" type="checkbox" id="allselect"  name="allselect" onclick="selectedAll()" ></div><div id="delselect" name="delselect" style="float:left; margin-left:10px; height:35px;line-height:35px; width:90px; border-radius:5px; border:1px; border-style:solid; border-color: #444444; color:#cccccc"  onclick="delSelect()" > <img src="img/yhgl_delete_normal.png"  style="vertical-align:middle; margin-right:5px; margin-left:20px; ">刪除</div></div>';
							
//單選
	function userCheck(ths) {
		if (ths.checked == false) {
			$("input[name=allselect]:checkbox").prop('checked', false);
		} else {
			var count = $("input[name='id']:checkbox:checked").length;
			if (count == $("input[name='id']:checkbox").length) {
				$("input[name=allselect]:checkbox").prop("checked", true);
			}
		}
	}

	//多選
	function selectedAll() {
		var select = $("input[name='allselect']").is(':checked');
		if (select) {
			$("input[type='checkbox']").prop("checked", true);
		} else {
			$("input[type='checkbox']").prop("checked", false);
		}
	}