I have a scenario where I am dynamically creating child buttons for a parent section, and I need to manage the state of the parent based on whether the child sections are selected or unselected. The parent should only be enabled when all child buttons are unselected. However, my current approach is not working as expected: when I unselect one child, the parent remains disabled, even though other children are still unselected.
below is code:
const configComboBoxEvent = function(calendar, controller, storeId, sectionId, errorLog){
// 店舗名の変更時の処理
$(storeId).on('change', function() {
const selectedStoreId = $(this).val(); // Get the storeId value from the select input
if (selectedStoreId) {
$.ajax({
url: `/${controller}/xxx`,
type: 'POST',
data: { storeId: selectedStoreId },
dataType: "json",
cache: false
})
.done(function(data) {
$(sectionId).empty();
let ids = [];
let parentSections = {}; // Store sections grouped by their parent section
let childSections = {}; // Store child sections by their parent
data.forEach(function(item) {
if (item.section_groups && item.section_groups.section_children_id) {
let childrenIds = item.section_groups.section_children_id.split(',');
// Group parent section with its children
parentSections[item.id] = {
section_name: item.section_name,
children: childrenIds
};
childrenIds.forEach(function(childId) {
childSections[childId] = true;
});
} else {
// If section has no children, just display as a separate section (if not already a child)
if (!childSections[item.id]) {
const button = $('<div/>', {
text: item.section_name,
'id': item.id,
'class': 'button-location-style',
click: function() {
var index = ids.indexOf(item.id);
if (index > -1) {
ids.splice(index, 1);
$(this).removeClass("changedBackground");
} else {
ids.push(item.id);
$(this).addClass("changedBackground");
}
$('#SectionId').attr('value', ids.join(','));
}
});
$(sectionId).append(button);
}
}
});
// Add parent sections with children below them
Object.keys(parentSections).forEach(function(parentId) {
const parent = parentSections[parentId];
// Create the parent section button
const parentButton = $('<div/>', {
text: parent.section_name,
'id': parentId,
'class': 'button-location-style parent-section',
click: function() {
var index = ids.indexOf(parentId);
if (index > -1) {
ids.splice(index, 1);
$(this).removeClass("changedBackground");
// Enable the child sections when the parent is unselected
parent.children.forEach(function(childId) {
$(`#${childId}`).removeClass('disabled');
});
} else {
ids.push(parentId);
$(this).addClass("changedBackground");
// Disable the child sections when the parent is selected
parent.children.forEach(function(childId) {
$(`#${childId}`).addClass('disabled');
});
}
// Update the section ID input field with the selected IDs
$('#SectionId').attr('value', ids.join(','));
}
});
$(sectionId).append(parentButton);
// Create a container for child sections under the parent button
const childContainer = $('<div/>', {
'class': 'child-container'
});
// Append child sections under the parent section
parent.children.forEach(function(childId) {
// Find the child section from the data
const childItem = data.find(function(item) {
return item.id == childId;
});
if (childItem) {
const childButton = $('<div/>', {
text: childItem.section_name,
id: childItem.id,
class: 'button-location-style child-section',
click: function () {
// check whether the child is in the selected array or not
var index = ids.indexOf(childItem.id);
if (index > -1) {
// if selected then unselect it
ids.splice(index, 1);
$(this).removeClass("changedBackground");
} else {
// otherwise select it
ids.push(childItem.id);
$(this).addClass("changedBackground");
}
// if ids array length > 0, disable the parent.
if (ids.length > 0) {
$(`#${parentId}`).addClass('disabled');
} else {
// otherwise, enable it.
$(`#${parentId}`).removeClass('disabled');
}
// Update the SectionId field
$('#SectionId').attr('value', ids.join(','));
}
});
// Append the child button to the container
childContainer.append(childButton);
}
});
$(sectionId).append(childContainer); // Append child container under parent
});
if (data.length === 0) {
const button = $('<div/>', {
text: 'xxx',
'class': 'button-location-style disabled',
});
$(sectionId).append(button);
}
})
.fail(function() {
alert("Error loading data.");
});
} else {
alert("Please select a valid store ID.");
}
});
}
Problem:
- The parent section should be enabled only when all child sections are
unselected. - The parent is not behaving as expected. After selecting multiple
children and unselecting one, the parent remains disabled even though
all child sections should not be selected.
What I have tried:
- I have checked the ids array when a child is selected or unselected,
but the parent is still not enabled when all children are unselected.
How can I modify my code so that the parent section only gets enabled when all child sections are unselected, and stays disabled when any child section is selected?
2
Single Parent
You could move your enable/disable logic in one sport. This way, after you have added/removed a child from the ids
array you update the parent.
Example:
if (childItem) {
const childButton = $('<div/>', {
text: childItem.section_name,
id: childItem.id,
class: 'button-location-style child-section',
click: function () {
// check whether the child is in the selected array or not
var index = ids.indexOf(childItem.id);
if (index > -1) {
// if selected then unselect it
ids.splice(index, 1);
$(this).removeClass("changedBackground");
} else {
// otherwise select it
ids.push(childItem.id);
$(this).addClass("changedBackground");
}
// decide whether to enable or disable the parent
// parent should be disabled if ANY child is selected
// if ids array length > 0, disable the parent.
if (ids.length > 0) {
$(`#${parentId}`).addClass('disabled');
} else {
// otherwise, enable it.
$(`#${parentId}`).removeClass('disabled');
}
// Update the SectionId field
$('#SectionId').attr('value', ids.join(','));
}
});
// Append the child button to the container
childContainer.append(childButton);
}
Multiple parents
This case is slightly different, because you need to track child selections per parent.
To each child we can add a parentId
property, which acts as a key to refer to its own parent.
Example:
First create an object/map to track selected children per parent id.
// key: parentId, value: array of child IDs selected for that parent
const selectedChildren = {};
Then, on creating the child button, you’ll also check for the parentId
property to manage selections in the right array.
if (childItem) {
const parentId = childItem.parentId; // or any name you want
// initialize an array of children, in the event the parent was missing
if (!selectedChildren[parentId]) {
selectedChildren[parentId] = [];
}
const childButton = $('<div/>', {
text: childItem.section_name,
id: childItem.id,
class: 'button-location-style child-section',
click: function() {
// get the parent’ selection array
const parentArray = selectedChildren[parentId];
const childIndex = parentArray.indexOf(childItem.id);
// if we found a child then unselect it
if (childIndex > -1) {
// unselect the child
parentArray.splice(childIndex, 1);
$(this).removeClass("changedBackground");
} else {
// otherwise select it
parentArray.push(childItem.id);
$(this).addClass("changedBackground");
}
// decide whether the parent should be disabled or not.
// If there are ANY selected children in parentArray, the parent remains disabled.
if (parentArray.length > 0) {
$(`#${parentId}`).addClass('disabled');
} else {
$(`#${parentId}`).removeClass('disabled');
}
// if needed, update the hidden input with the full selected IDs across all parents
// otherwise you only need the currently selected children for THIS parent,
// then you can store just parentArray.
// otherwise, to show *all* selected IDs, you can combine them:
const allSelectedIds = Object.values(selectedChildren).flat();
$('#SectionId').val(allSelectedIds.join(','));
}
});
// Append the child button to the container
childContainer.append(childButton);
}
2
You can define a hierarchy of templates, a way for find enabled descendants and enable/disable based on their existence, like the below.
function getTemplate(json) {
let rows = [];
for (let row of json) {
rows.push(`
<div class="node">
<label>
${row.text}
<input type="checkbox" ${row.checked ? "checked" : ""} onchange="handleEnabled(root);">
</label>
<div class="children">
${getTemplate(row.children)}
</div>
</div>
`);
}
return rows.join("");
}
function handleEnabled(root) {
for (let node of root.querySelectorAll("input[type=checkbox]")) {
let enabledDescendant = false;
for (let innerNode of node.parentNode.parentNode.children[1].querySelectorAll(".children input[type=checkbox]")) {
enabledDescendant = enabledDescendant || innerNode.checked;
}
if (enabledDescendant) {
node.disabled = true;
} else {
node.disabled = false;
}
}
}
let root = document.getElementById("container");
root.innerHTML = getTemplate([
{
text: "a",
checked: false,
children: [
{
text: "aa",
checked: true,
children: []
},
{
text: "ab",
checked: false,
children: []
},
{
text: "ac",
checked: false,
children: [
{
text: "aca",
checked: false,
children: []
},
{
text: "acb",
checked: false,
children: []
},
{
text: "acc",
checked: false,
children: []
},
]
},
]
},
{
text: "b",
checked: false,
children: []
},
{
text: "c",
checked: false,
children: []
}
]);
handleEnabled(root);
.node {
margin-left: 5px;
}
<div id="container"></div>
This is pure Javascript and of course you can do it in jQuery too by using #(...)
instead of querySelectorAll
and prop()
to set the disabled status, but I decided to do it in pure JS to make sure the solution is useful for non-jQuery users too.
1
You question becomes a bit theoretical now that you haven’t included HTML in you code. But I hope that the following example could make sense in your case.
I have checkboxes in a form, all named “item” except the first name “selectall”. When “selectall” is changed either all or none should be checked. When (any) “item” is changed, “selectall” should be checked if all “item” are checked, else not checked.
document.forms.form01.addEventListener('change', change_handler);
function change_handler(e) {
let form = e.target.form;
// items need to be an array, even when there is only one item
let items = (form.item.length) ? form.item : [form.item];
switch (e.target.name) {
case 'selectall':
let checked = e.target.checked;
// all items should be the same as "selectall"
[...items].forEach(item => item.checked = checked);
break;
case 'item':
// decide if "selectall" should be selected or not
let allchecked = ([...items].filter(item => !item.checked).length == 0) ?? true;
form.selectall.checked = allchecked ? true : false;
break;
}
}
<form name="form01">
<label>Select all<input type="checkbox" name="selectall"></label>
<label>Item 1<input type="checkbox" name="item"></label>
<label>Item 2<input type="checkbox" name="item"></label>
<label>Item 3<input type="checkbox" name="item"></label>
</form>