<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<label for="btnq">
<input type="checkbox" id="btnq" class="btnQ"/>全選</label>
<button class="del">刪除</button>
<button class="queren">確認</button>
<button class="btnHZ">獲取選中的值</button>
<div>
<label for="userName">
<input type="checkbox" id="userName" name="test" class="cb_fruit" value="1"/>userName
</label>
<label for="userPhone">
<input type="checkbox" id="userPhone" name="test" class="cb_fruit" value="2"/>userPhone
</label>
<label for="userAddress">
<input type="checkbox" id="userAddress" name="test" class="cb_fruit" value="3"/>userAddress
</label>
<label for="userSize">
<input type="checkbox" id="userSize" name="test" class="cb_fruit" value="4"/>userSize
</label>
<label for="userColer">
<input type="checkbox" id="userColer" name="test" class="cb_fruit" value="5"/>userColer
</label>
</div>
</body>
</html>
<script src="js/jquery.js"></script>
<script>
$(function () {
//獲取選中的值
var intName = document.getElementsByName("test");
$(".btnHZ").click(function () {
intVal()
});
function intVal(){
var intArr = [];
for (k in intName) {
if (intName[k].checked) {
intArr.push(intName[k].value)
}
}
console.log(intArr)
}
//確認
$(".queren").click(function () {
if ($("input[name=`test`]:checked").length == 0) {
alert("請選中資訊")
}else{
intVal();
}
});
//全選和反選
$(".btnQ").click(function () {
$("input[name=`test`]").prop("checked", this.checked);
});
/*挨個選完選中後全選選中,取消一個選中全選取消選中*/
$(".cb_fruit").change(function () {
if ($("input[name=`test`]:checked").length == $(".cb_fruit").length) {
$("#btnq").prop("checked", true);
} else {
$("#btnq").prop("checked", false);
}
});
//刪除
$(".del").click(function () {
if ($("input[name=`test`]:checked").length == 0) {
alert("請選中刪除項")
} else {
$("div input").each(function () {
if ($(this).is(`:checked`)) {
$(this).remove();
}
})
}
});
})
</script>