function handleLevelOneChange(parentDropdown, choices, container, field, alldata) {
// Remove nested dropdowns beyond the first level
removeNestedDropdowns(container, field.name, 1);
// Get the selected value from the dropdown
const selectedValue = parentDropdown.value;
const selectedChoice = findChoiceByValue(selectedValue, choices);
// Ensure field.nested_fields exists and has at least one entry
if (selectedChoice && Array.isArray(field.nested_fields) && field.nested_fields[0]) {
const levelTwoFieldName = field.nested_fields[0].name;
code
// Safeguard: Check if `alldata.mandatory_fields` is valid and contains the required field
const initialLevelTwo = alldata.mandatory_fields ? alldata.mandatory_fields[levelTwoFieldName] : null;
// Create the second-level dropdown
createLevelTwoDropdown(container, selectedChoice, field, alldata, initialLevelTwo);
} else {
console.error(Invalid nested fields or missing data for field: ${field.name}.);
}
function handleLevelTwoChange(parentDropdown, choices, container, field, alldata) {
// Remove nested dropdowns beyond the second level
removeNestedDropdowns(container, field.name, 2);
// Get the selected value and choice
const selectedValue = parentDropdown.value;
const selectedChoice = findChoiceByValue(selectedValue, choices);
// Update the selected mandatory fields
selectedMandatoryFields[field.nested_fields[0].name] = selectedValue;
// Check if nested_fields exists, is an array, and has at least two elements
if (
selectedChoice &&
selectedChoice.nested_options &&
Array.isArray(field.nested_fields) &&
field.nested_fields.length > 1
) {
const levelThreeFieldName = field.nested_fields[1].name;
code
// Safeguard: Check if alldata.mandatory_fields is valid and contains the required field
const initialLevelThree = alldata.mandatory_fields
? alldata.mandatory_fields[levelThreeFieldName]
: null;
// Create the third-level dropdown
createLevelThreeDropdown(container, selectedChoice, field, alldata, initialLevelThree);
// Remove the entire field container
container.parentNode.removeChild(container);
console.log("Remaining selectedMandatoryFields:", selectedMandatoryFields);
}
function removeNestedDropdowns(container, fieldName, level) {
const children = container.querySelectorAll(fw-select[name^="${fieldName}_level_"]);
children.forEach(child => {
const childLevel = parseInt(child.getAttribute('name').split('_').pop(), 10);
if (childLevel > level) {
delete selectedMandatoryFields[child.getAttribute('name')];
container.removeChild(child);
}
});
}
function populateDropdown(dropdown, choices) {
if (!Array.isArray(choices)) {
console.error('Choices is not an array:', choices);
return;
}
choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.value); // Updated to use value instead of id
option.textContent = choice.value;
dropdown.appendChild(option);
});
}
function findChoiceByValue(value, choices) {
for (const choice of choices) {
if (choice.value == value) { // Updated to compare value
return choice;
}
if (choice.nested_options) {
const result = findChoiceByValue(value, choice.nested_options);
if (result) {
return result;
}
}
}
return null;
}
in this, when i change 1st dropdown, 2nd dropdown should create as new
In the implementation of your dependent dropdowns, it looks like you've already accounted for removing and recreating the second dropdown whenever the first dropdown changes. Specifically, the logic inside the handleLevelOneChange and removeNestedDropdowns functions handles cleaning up existing nested dropdowns and labels. However, you might not be refreshing the state of the second dropdown properly or may want to ensure everything is being reset for new selections in the first dropdown.
Let me guide you on how to ensure the second dropdown (or other nested levels) is recreated and works cleanly when the first dropdown's value changes.
Key Points to Ensure the Behavior:
Remove All Nested Dropdowns Effectively:
When the first dropdown changes, all dependent dropdowns (second-level, third-level, etc.) must be removed so they can be recreated from scratch. This is already handled via the removeNestedDropdowns function.
Recreate Second Dropdown:
When a new value is selected in the first dropdown, the second dropdown should be created as per the selection using fresh data.
Reset State for Non-Selected Values:
If the user changes selection in the first dropdown, the previously selected value of the second dropdown should be cleared and the selectedMandatoryFields object should be updated accordingly.
Here's the modified logic for handleLevelOneChange:
Updated Implementation
javascript
function handleLevelOneChange(parentDropdown, choices, container, field, alldata) {
// Clear nested dropdowns starting at the first level
removeNestedDropdowns(container, field.name, 1);
// Get the selected value from the first dropdown
const selectedValue = parentDropdown.value;
const selectedChoice = findChoiceByValue(selectedValue, choices);
// Update the selected mandatory fields for the first dropdown
selectedMandatoryFields[field.name] = selectedValue;
// Ensure `nested_fields` exists and has valid data to proceed to the next level
if (selectedChoice && Array.isArray(field.nested_fields) && field.nested_fields[0]) {
const levelTwoFieldName = field.nested_fields[0].name;
// Safeguard: Check if `alldata.mandatory_fields` contains preset data
const initialLevelTwo = alldata.mandatory_fields ? alldata.mandatory_fields[levelTwoFieldName] : null;
// Create the second dropdown (Level 2)
createLevelTwoDropdown(container, selectedChoice, field, alldata, initialLevelTwo);
} else {
console.warn(`No nested fields available for field: ${field.name}. Clearing dependents.`);
}
// Log the updated state of selected mandatory fields
console.log("Updated selectedMandatoryFields: ", selectedMandatoryFields);
}
Points Addressed in the Code Above:
When the first dropdown changes:
Invoke removeNestedDropdowns to clean up any second-level (or deeper) dropdowns.
Recreate the second dropdown using createLevelTwoDropdown.
If there is no valid nested data:
Warn the console and stop further dropdown creation—this avoids errors with unexpected nulls.
Update the global state selectedMandatoryFields for the level one dropdown correctly.
Create the Second-Level Dropdown (createLevelTwoDropdown):
This function is already well-defined in your implementation, and it follows the pattern for recursive creation of dependent dropdowns. Ensure that it is called appropriately when the first dropdown changes.
Key Function to Clear Dependent Dropdowns:
The removeNestedDropdowns function is essential in making sure old dropdowns (from previous selections) are removed before creating new ones. This implementation looks sufficient.
javascript
function removeNestedDropdowns(container, fieldName, level) {
const children = container.querySelectorAll(`fw-select[name^="${fieldName}_level_"]`);
children.forEach((child) => {
const childLevel = parseInt(child.getAttribute('name').split('_').pop(), 10);
if (childLevel >= level) {
// Remove the dropdown only if its level is >= the specified level
delete selectedMandatoryFields[child.getAttribute('name')];
container.removeChild(child);
}
});
}
Demo Flow of Execution:
User Selects an Option in First Dropdown:
handleLevelOneChange is called via the fwChange event listener.
Existing nested fields are removed via removeNestedDropdowns.
The second dropdown is created (or skipped if no valid nested fields exist).
User Changes Selection in First Dropdown:
handleLevelOneChange is triggered again.
This recursively resets and recreates the dropdown hierarchy beyond the first level.
Second Dropdown Updates State:
The update propagates to deeper levels (if any) similarly.
Debug These Scenarios:
Ensure that the populateDropdown function correctly populates the dropdown with new data for both first and second dropdowns. Verify the choices object passed to this function.
Verify that findChoiceByValue finds the correct parent choice when navigating nested data.
Ensure that selectedMandatoryFields reflects accurate values for each level as changes happen.
If this still doesn't resolve specific issues, let me know exactly which part fails or behaves unexpectedly!
function handleLevelOneChange(parentDropdown, choices, container, field, alldata) {
// Remove nested dropdowns beyond the first level
removeNestedDropdowns(container, field.name, 1);
// Get the selected value from the dropdown
const selectedValue = parentDropdown.value;
const selectedChoice = findChoiceByValue(selectedValue, choices);
// Ensure field.nested_fields exists and has at least one entry
if (selectedChoice && Array.isArray(field.nested_fields) && field.nested_fields[0]) {
const levelTwoFieldName = field.nested_fields[0].name;
code
// Safeguard: Check if `alldata.mandatory_fields` is valid and contains the required field
const initialLevelTwo = alldata.mandatory_fields ? alldata.mandatory_fields[levelTwoFieldName] : null;
// Create the second-level dropdown
createLevelTwoDropdown(container, selectedChoice, field, alldata, initialLevelTwo);
} else {
console.error(Invalid nested fields or missing data for field: ${field.name}.);
}
function handleLevelTwoChange(parentDropdown, choices, container, field, alldata) {
// Remove nested dropdowns beyond the second level
removeNestedDropdowns(container, field.name, 2);
// Get the selected value and choice
const selectedValue = parentDropdown.value;
const selectedChoice = findChoiceByValue(selectedValue, choices);
// Update the selected mandatory fields
selectedMandatoryFields[field.nested_fields[0].name] = selectedValue;
// Check if nested_fields exists, is an array, and has at least two elements
if (
selectedChoice &&
selectedChoice.nested_options &&
Array.isArray(field.nested_fields) &&
field.nested_fields.length > 1
) {
const levelThreeFieldName = field.nested_fields[1].name;
code
// Safeguard: Check if alldata.mandatory_fields is valid and contains the required field
const initialLevelThree = alldata.mandatory_fields
? alldata.mandatory_fields[levelThreeFieldName]
: null;
// Create the third-level dropdown
createLevelThreeDropdown(container, selectedChoice, field, alldata, initialLevelThree);
// Remove the entire field container
container.parentNode.removeChild(container);
console.log("Remaining selectedMandatoryFields:", selectedMandatoryFields);
}
function removeNestedDropdowns(container, fieldName, level) {
const children = container.querySelectorAll(fw-select[name^="${fieldName}_level_"]);
children.forEach(child => {
const childLevel = parseInt(child.getAttribute('name').split('_').pop(), 10);
if (childLevel > level) {
delete selectedMandatoryFields[child.getAttribute('name')];
container.removeChild(child);
}
});
}
function populateDropdown(dropdown, choices) {
if (!Array.isArray(choices)) {
console.error('Choices is not an array:', choices);
return;
}
choices.forEach(choice => {
const option = document.createElement('fw-select-option');
option.setAttribute('value', choice.value); // Updated to use value instead of id
option.textContent = choice.value;
dropdown.appendChild(option);
});
}
function findChoiceByValue(value, choices) {
for (const choice of choices) {
if (choice.value == value) { // Updated to compare value
return choice;
}
if (choice.nested_options) {
const result = findChoiceByValue(value, choice.nested_options);
if (result) {
return result;
}
}
}
return null;
}
in ths, when i change 1st dropdown, 2nd dropdown creates but it label has 2nd dropdown and third dropdown labels append next to 2nd label in 2nd dropdown. then choose , the third dropdown shows as dropdown without label that should not show like that. if i change 1st dropdown, 2nd dropdown should create with 2nd label only,
The issue you are facing stems from the fact that when you change the first dropdown, new labels for the dependent dropdowns are appended without fully clearing the existing labels and dropdowns. As a result, labels for nested dropdowns (like the label for the third level) are rendered alongside the second dropdown, and the third dropdown shows up without its associated label.
Let's fix this!
Detailed Resolution
When handling changes in the first dropdown, the following key steps must be enforced:
Remove All Existing Dependent Labels and Dropdowns (Beyond the Level Being Modified) Effectively
The current implementation (removeNestedDropdowns) removes dependent dropdowns (fw-select) correctly, but it does not remove the labels (or removes them inconsistently). This means old labels remain appended to the container when new dropdowns are generated.
Update the removeNestedDropdowns function to remove associated labels for all dropdowns beyond the given level.
Ensure Labels and Dropdowns Are Created Separately for Each Level
When creating each dropdown (e.g., the second dropdown in createLevelTwoDropdown), you should first ensure that any invalid or previously created labels are removed.
Prevent Third-Level Dropdown Creation If Data is Invalid
Ensure the logic gracefully halts further dropdown creation if the second dropdown is selected and no valid data is available for the next level.
Updated Logic
Fix 1: Update removeNestedDropdowns to Remove Labels
Modify your removeNestedDropdowns function to additionally search for and remove label elements associated with the dropdowns:
javascript
function removeNestedDropdowns(container, fieldName, level) {
const elementsToRemove = container.querySelectorAll(
`fw-select[name^="${fieldName}_level_"], label[for^="${fieldName}_level_"]`
);
// Loop through and remove all dropdowns and their corresponding labels beyond the given level
elementsToRemove.forEach((element) => {
const name = element.getAttribute('name') || element.getAttribute('for');
if (name) {
const childLevel = parseInt(name.split('_').pop(), 10);
if (childLevel > level) {
// Remove element and clean state
delete selectedMandatoryFields[name];
container.removeChild(element);
}
}
});
}
This ensures that both fw-select dropdowns and their associated label elements are removed when a higher-level dropdown value changes.
Fix 2: Enforce Clean Label Rendering in createLevelTwoDropdown
Before creating a new label for the second-level dropdown, confirm that any pre-existing label for the field.name_level_2 is removed. Use this logic:
But before appending the above label, if it's already there (from an earlier interaction), remove it first. Modify the removeNestedDropdowns logic to ensure labels specific to this level are removed dynamically.
Fix 3: Halt Invalid Dropdown Generation
Within handleLevelOneChange and handleLevelTwoChange, if the choices or nested_options for the next dropdown do not exist, explicitly stop creating that dropdown. Otherwise, empty dropdowns will be added without labels.
For example:
javascript
if (!selectedChoice || !selectedChoice.nested_options) {
console.warn(
`No nested options available for field ${field.name} at level ${field.nested_fields[0]?.name}`
);
return; // Do not proceed further since there are no valid nested fields
}
Final Updated Functions
Here are the adjusted functions that behave as per your requirement:
1. Updated handleLevelOneChange
javascript
function handleLevelOneChange(parentDropdown, choices, container, field, alldata) {
// Clear nested dropdowns starting at the first level
removeNestedDropdowns(container, field.name, 1);
// Get the selected value from the first dropdown
const selectedValue = parentDropdown.value;
const selectedChoice = findChoiceByValue(selectedValue, choices);
// Update the selected mandatory fields for the first dropdown
selectedMandatoryFields[field.name] = selectedValue;
// Create the second dropdown only if valid nested fields exist
if (selectedChoice && Array.isArray(field.nested_fields) && field.nested_fields[0]) {
const levelTwoFieldName = field.nested_fields[0].name;
// Fetch initial preset data for level 2, if available
const initialLevelTwo = alldata.mandatory_fields
? alldata.mandatory_fields[levelTwoFieldName]
: null;
// Create the second dropdown (Level 2)
createLevelTwoDropdown(container, selectedChoice, field, alldata, initialLevelTwo);
} else {
console.warn(`No valid nested fields available for field: ${field.name}`);
}
console.log("Updated selectedMandatoryFields: ", selectedMandatoryFields);
}
2. Updated createLevelTwoDropdown
javascript
function createLevelTwoDropdown(container, selectedChoice, field, alldata, initialValue) {
// Ensure proper removal of existing second-level dropdown and label
removeNestedDropdowns(container, field.name, 2);
// Dynamically create and render the label for the second-level dropdown
const levelTwoLabelElement = document.createElement("label");
levelTwoLabelElement.style.marginTop = "16px";
levelTwoLabelElement.innerHTML = `${field.nested_fields[0].label} <span style="color: red;">*</span>`;
levelTwoLabelElement.setAttribute("for", `${field.name}_level_2`);
levelTwoLabelElement.style.marginLeft = "20px";
levelTwoLabelElement.style.marginBottom = "3px";
levelTwoLabelElement.style.fontWeight = "600";
container.appendChild(levelTwoLabelElement);
// Create the second-level dropdown
const nestedSelect = document.createElement("fw-select");
nestedSelect.setAttribute("name", `${field.name}_level_2`);
nestedSelect.setAttribute("placeholder", `Select ${selectedChoice.label || "an option"}`);
nestedSelect.setAttribute("hint-text", "Select singular option");
nestedSelect.classList.add("ms-3", "my-2"); // Bootstrap classes for margin
// Populate options for the second dropdown
populateDropdown(nestedSelect, selectedChoice.nested_options);
container.appendChild(nestedSelect);
// Set initial value and add change handler
if (initialValue) {
nestedSelect.value = initialValue;
handleLevelTwoChange(nestedSelect, selectedChoice.nested_options, container, field, alldata);
}
nestedSelect.addEventListener("fwChange", (event) => {
const selectedValue = event.detail.value;
selectedMandatoryFields[field.nested_fields[0].name] = selectedValue;
handleLevelTwoChange(nestedSelect, selectedChoice.nested_options, container, field, alldata);
});
}
Key Behavior After Fixes
When the first dropdown is changed:
All dependent dropdowns and labels (second level and beyond) are cleared completely.
Only the correct second-level dropdown and its label are rendered.
When the second dropdown is changed:
Any dropdown beyond the second level (third level, etc.) is cleared.
New dependent dropdowns are rendered properly, with their corresponding labels.
Invalid data halts further dropdown creation (no unlabelled dropdowns).
Let me know if you face any issues! 😊
The reason why, when you change the first dropdown, the second dropdown creates but incorrectly contains both the second and third dropdown labels is that your current implementation incorrectly appends labels without fully clearing all nested labels associated with dependent dropdown fields.
This issue arises due to one (or both) of the following conditions:
Labels from previously created dropdowns (second-level, third-level, etc.) are not fully removed when the first dropdown is changed.
New labels are incorrectly appended, even when the correct label for the second dropdown already exists.
We need to ensure that all nested labels and dropdowns are removed when the dropdown hierarchy changes.
Fixing the Issue
The solution can be broken down into steps:
Ensure Proper Cleanup of Nested Labels and Dropdowns
Use a function to remove all dropdowns and their labels beyond the level that is being selected. This will prevent labels (for third-level dropdowns in this case) from persisting when rebuilding the second dropdown.
Check for Preexisting Labels Before Adding New Ones
Any time you create a second or third dropdown, first check if a label for the dropdown already exists in the DOM. If it does, remove it to ensure no duplication.
Stop Propagating to Third Level Until Second Level Dropdown Selection is Valid
Prevent unnecessary creation of labels or dropdowns for levels beyond the second level until the second dropdown’s value has been selected.
Let’s fix this issue step-by-step by modifying your code.
Updated Code
1. Update removeNestedDropdowns to Remove Labels
The function to remove nested elements (removeNestedDropdowns) currently removes only the dropdowns (fw-select), but not their corresponding labels (label). Let’s fix that so all labels associated with dropdown levels beyond the given level are properly removed.
javascript
function removeNestedDropdowns(container, fieldName, level) {
const elementsToRemove = container.querySelectorAll(
`fw-select[name^="${fieldName}_level_"], label[for^="${fieldName}_level_"]`
);
elementsToRemove.forEach((element) => {
const name = element.getAttribute("name") || element.getAttribute("for");
if (name) {
const childLevel = parseInt(name.split("_").pop(), 10); // Extract level of the element
if (childLevel > level) {
// Remove element if its level is greater than the specified level
delete selectedMandatoryFields[name];
container.removeChild(element); // Remove both labels and dropdowns
}
}
});
}
Step 2: Avoid Label Duplication While Creating a Dropdown
When you create a new dropdown (like the second dropdown in createLevelTwoDropdown), ensure that no existing labels remain for that dropdown level before appending the new label.
Here’s how the second dropdown generation works:
Updated createLevelTwoDropdown
javascript
function createLevelTwoDropdown(container, selectedChoice, field, alldata, initialValue) {
// Remove any existing second-level dropdown and label
removeNestedDropdowns(container, field.name, 2);
// Dynamically create and render the label for the second-level dropdown
const existingLabel = container.querySelector(`label[for="${field.name}_level_2"]`);
if (!existingLabel) {
const levelTwoLabelElement = document.createElement("label");
levelTwoLabelElement.style.marginTop = "16px";
levelTwoLabelElement.innerHTML = `${field.nested_fields[0].label} <span style="color: red;">*</span>`;
levelTwoLabelElement.setAttribute("for", `${field.name}_level_2`);
levelTwoLabelElement.style.marginLeft = "20px";
levelTwoLabelElement.style.marginBottom = "3px";
levelTwoLabelElement.style.fontWeight = "600";
container.appendChild(levelTwoLabelElement);
}
// Create the dropdown for the second level
const nestedSelect = document.createElement("fw-select");
nestedSelect.setAttribute("name", `${field.name}_level_2`);
nestedSelect.setAttribute("placeholder", `Select ${selectedChoice.label || "an option"}`);
nestedSelect.setAttribute("hint-text", "Select singular option");
nestedSelect.classList.add("ms-3", "my-2"); // Bootstrap classes for margin
// Populate dropdown options based on the selected choice
populateDropdown(nestedSelect, selectedChoice.nested_options);
container.appendChild(nestedSelect);
// Set an initial value for the dropdown, if available
if (initialValue) {
nestedSelect.value = initialValue;
handleLevelTwoChange(nestedSelect, selectedChoice.nested_options, container, field, alldata);
}
// Add a change event listener to respond to user selection
nestedSelect.addEventListener("fwChange", (event) => {
const selectedValue = event.detail.value;
// Update the selected mandatory fields
selectedMandatoryFields[field.nested_fields[0].name] = selectedValue;
// Handle changes for deeper levels (third dropdown creation)
handleLevelTwoChange(nestedSelect, selectedChoice.nested_options, container, field, alldata);
});
}
Step 3: Stop Unnecessary Label Creation for Third Level Until Valid
When creating deeper dropdowns (like the third-level dropdown), verify first if valid options are available for rendering. If not, exit early to avoid showing an empty dropdown or unintentional labels.
Updated handleLevelTwoChange
javascript
function handleLevelTwoChange(parentDropdown, choices, container, field, alldata) {
// Remove nested dropdowns (third-level and beyond)
removeNestedDropdowns(container, field.name, 2);
// Get the selected value and corresponding choice
const selectedValue = parentDropdown.value;
const selectedChoice = findChoiceByValue(selectedValue, choices);
// Update the selected mandatory fields
selectedMandatoryFields[field.nested_fields[0].name] = selectedValue;
// Check if nested options exist for third-level creation
if (
selectedChoice &&
selectedChoice.nested_options &&
Array.isArray(field.nested_fields) &&
field.nested_fields.length > 1
) {
const levelThreeFieldName = field.nested_fields[1].name;
// Retrieve initial value for the third dropdown, if defined
const initialLevelThree = alldata.mandatory_fields
? alldata.mandatory_fields[levelThreeFieldName]
: null;
// Create the third-level dropdown
createLevelThreeDropdown(container, selectedChoice, field, alldata, initialLevelThree);
} else {
console.warn(`No valid nested options for field: ${field.nested_fields[0].name}`);
}
}
Expected Behavior After Fixes
When you change the first dropdown:
All dependent dropdowns (second-level and third-level) and their labels are completely removed, ensuring no duplicates.
Only the correct label and dropdown for the second-level are created.
When you select the second dropdown:
Any dropdown or label beyond the second-level (third-level) is cleared, and only valid options for deeper levels are rendered.
If there are no valid options for further levels:
Stop further dropdown creation and avoid appending any labels or dropdowns without data.
Debugging Steps
Inspect the DOM:
After changing the first dropdown, ensure there is only one label for the second dropdown (label[for="field_name_level_2"]).
Ensure all labels and dropdowns for third-level fields are removed when the first dropdown is changed.
Console Logs:
Add console.log statements in the removeNestedDropdowns, createLevelTwoDropdown, and handleLevelOneChange functions to verify each step works as expected.
Let me know if this resolves your issue or if additional clarification is needed! 😊