Skip to content

New refresh method with selection of the new element #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion DynamicSelect.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,29 @@ class DynamicSelect {
}
}

// New refresh method with selection of the new element
refresh(data, selectedValue = null) {
this.data = data; // Update the data

if (selectedValue) {
// Find the newly added element and mark it as selected
this.data.forEach(option => {
if (option.value === selectedValue) {
option.selected = true; // Mark this option as selected
} else {
option.selected = false; // Unselect others
}
});
}

const newElement = this._template(); // Create new HTML for the component
this.element.replaceWith(newElement); // Replace the current element with the new one
this.element = newElement; // Update the reference to the new element

this._updateSelected();
this._eventHandlers(); // Reattach event handlers
}

get selectedValue() {
let selected = this.data.filter(option => option.selected);
selected = selected.length ? selected[0].value : '';
Expand Down Expand Up @@ -180,4 +203,4 @@ class DynamicSelect {
}

}
document.querySelectorAll('[data-dynamic-select]').forEach(select => new DynamicSelect(select));
document.querySelectorAll('[data-dynamic-select]').forEach(select => new DynamicSelect(select));