I have multiple custom select drop downs in my app on screen at any given time. I ALSO inject new rows of content which contain more instances of these custom selects. However, anything loaded in via Fetch/AJAX is not working, obviously since those custom selects were not part of the original element list at runtime.
How can I modify this javascript to cater to both the custom selects on page load, PLUS any new ones added dynamically after the page loads?
let custom_selects = document.querySelectorAll(".custom-select");
custom_selects.forEach(element => element.addEventListener('click', e => {
// DO NOTHING IF DISABLED
if (element.disabled) return false;
// TOGGLE ACTIVE CLASS TO HIDE/SHOW DROPDOWN
element.classList.toggle('active');
// SET VARS
let choose = element.querySelector(".custom-select-choose");
let hidden_value = element.querySelector("input");
// IF CLICKING AN OPTION
if (e.target.matches("li")) {
// SET THE VARS
let select_text = e.target.innerText;
let select_value = e.target.dataset.value;
// UPDATE WHAT'S DISPLAYED
choose.textContent = select_text;
// UPDATE THE HIDDEN INPUT
hidden_value.value = select_value;
}
}))
And this is the js that inserts a new row into my page…
///////////////////////
// ADD NEW LINE ITEM //
///////////////////////
if (e.target.matches('#new-line-item')) {
// GET THE ID OF CURRENT PROJECT OFF THE BUTTON
let project_id = e.target.dataset.project;
// INSERT AND RETURN THE EMPTY LINE ITEM
fetch(project_id+"/cost-add", { headers: {"X-Requested-With": "XMLHttpRequest", 'Content-Type': 'application/x-www-form-urlencoded'}})
.then(response => response.json())
.then(function(data) {
if (data.status == "success") {
// ADD NEW LINE TO FORM
e.target.insertAdjacentHTML('beforebegin', data.html);
}
// IF ERROR, DISPLAY
else {
error_in_results(data.html);
}
});
e.preventDefault();
e.stopPropagation();
}
Any help or advice is greatly appreciated.