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:
if (childItem) {
const childButton = $('<div/>', {
text: childItem.section_name,
'id': childItem.id,
'class': 'button-location-style child-section',
click: function() {
var index = ids.indexOf(childItem.id);
if (index > -1) {
// Unselect the child
ids.splice(index, 1);
$(this).removeClass("changedBackground");
// Enable the parent section when the child is unselected
$(`#${parentId}`).removeClass('disabled');
} else {
// Select the child
ids.push(childItem.id);
$(this).addClass("changedBackground");
// Disable the parent section when the child is selected
$(`#${parentId}`).addClass('disabled');
}
// Update the section ID input field with the selected IDs
$('#SectionId').attr('value', ids.join(','));
}
});
// Append the child button to the container
childContainer.append(childButton);
}
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?