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:
What I have tried:
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?
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);
}
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);
}