jQueryを使用してIntermediateプロパティですべてをチェック/チェック解除する
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));
}
});