jQuery를 사용하여 중간 속성으로 모두 확인 / 선택 취소
getSelectedItems () 메소드를 사용하여 배열에서 점검 항목 가져 오기
소스 체크 박스리스트 불확정 마스터 체크로 모두 선택 / 선택 해제
HTML
<div class="container">
<div class="card">
<div class="card-header">
<ul class="list-group list-group-flush">
<li class="list-group-item">
<input
class="form-check-input"
type="checkbox"
value="selectAll"
id="masterCheck"
/>
<label class="form-check-label" for="masterCheck">
Select / Unselect All
</label>
</li>
</ul>
</div>
<div class="card-body">
<ul class="list-group list-group-flush" id="list-wrapper">
<li class="list-group-item">
<input
class="form-check-input"
type="checkbox"
value="item1"
id="item1"
/>
<label class="form-check-label" for="item1">
Item 1
</label>
</li>
<li class="list-group-item">
<input
class="form-check-input"
type="checkbox"
value="item2"
id="item2"
/>
<label class="form-check-label" for="item2">
Item 2
</label>
</li>
<li class="list-group-item">
<input
class="form-check-input"
type="checkbox"
value="item3"
id="item3"
/>
<label class="form-check-label" for="item3">
Item 3
</label>
</li>
<li class="list-group-item">
<input
class="form-check-input"
type="checkbox"
value="item4"
id="item4"
/>
<label class="form-check-label" for="item4">
Item 4
</label>
</li>
<li class="list-group-item">
<input
class="form-check-input"
type="checkbox"
value="item5"
id="item5"
/>
<label class="form-check-label" for="item5">
Item 5
</label>
</li>
<li class="list-group-item" id="selected-values"></li>
</ul>
</div>
</div>
</div>
jQuery
$(function() {
// ID selector on Master Checkbox
var masterCheck = $("#masterCheck");
// ID selector on Items Container
var listCheckItems = $("#list-wrapper :checkbox");
// Click Event on Master Check
masterCheck.on("click", function() {
var isMasterChecked = $(this).is(":checked");
listCheckItems.prop("checked", isMasterChecked);
getSelectedItems();
});
// Change Event on each item checkbox
listCheckItems.on("change", function() {
// Total Checkboxes in list
var totalItems = listCheckItems.length;
// Total Checked Checkboxes in list
var checkedItems = listCheckItems.filter(":checked").length;
//If all are checked
if (totalItems == checkedItems) {
masterCheck.prop("indeterminate", false);
masterCheck.prop("checked", true);
}
// Not all but only some are checked
else if (checkedItems > 0 && checkedItems < totalItems) {
masterCheck.prop("indeterminate", true);
}
//If none is checked
else {
masterCheck.prop("indeterminate", false);
masterCheck.prop("checked", false);
}
getSelectedItems();
});
function getSelectedItems() {
var getCheckedValues = [];
getCheckedValues = [];
listCheckItems.filter(":checked").each(function() {
getCheckedValues.push($(this).val());
});
$("#selected-values").html(JSON.stringify(getCheckedValues));
}
});