Dynamic Dropdown without JQuery
I have 2 dynamic dropdowns that are placed on the end of a form (simple_form). The select works only once. If I select once more optgroups1 and optgroups2 is empty. On load both variables are set as expected.
const optgroups1 = document.getElementById('pos_select').getElementsByTagName('optgroup');
let sel = document.getElementById('candidate_functionalarea_id');
sel.addEventListener("change", function () {
let evnt = document.getElementById("candidate_functionalarea_id");
let options = dyndrop(optgroups1, evnt);
document.getElementById('candidate_positioncategory_id').innerHTML = options;
});
const optgroups2 = document.getElementById('tag_select').getElementsByTagName('optgroup');
let sel2 = document.getElementById('candidate_function_id');
sel2.addEventListener("change", function () {
let evnt2 = document.getElementById("candidate_functionalarea_id");
let options = dyndrop(optgroups2, evnt2);
document.getElementById('candidate_positioncategory_id').innerHTML = options;
});
function dyndrop(optgroups, evnt) {
let option_text = evnt.options[evnt.selectedIndex].text;
let option_id = evnt.options[evnt.selectedIndex].value;
let options;
for (let i = 0; i < optgroups.length; i++) {
if (optgroups[i].label == option_text) {
options = optgroups[i].innerHTML;
}
}
return options;
};
I have changed it a bit but the problem remains.
document.addEventListener('DOMContentLoaded', function () {
const optgroups1 = document.getElementById('pos_select').getElementsByTagName('optgroup');
let sel = document.getElementById('candidate_functionalarea_id');
sel.addEventListener("change", function () {
let evnt = document.getElementById("candidate_functionalarea_id");
let options = dyndrop(optgroups1, evnt);
document.getElementById('candidate_positioncategory_id').innerHTML = options;
});
const optgroups2 = document.getElementById('tag_select').getElementsByTagName('optgroup');
let sel2 = document.getElementById('candidate_function_id');
sel2.addEventListener("change", function () {
let evnt2 = document.getElementById("candidate_functionalarea_id");
let options = dyndrop(optgroups2, evnt2);
document.getElementById('candidate_positioncategory_id').innerHTML = options;
});
function dyndrop(optgroups, evnt) {
let option_text = evnt.options[evnt.selectedIndex].text;
let option_id = evnt.options[evnt.selectedIndex].value;
let options;
for (let i = 0; i < optgroups.length; i++) {
if (optgroups[i].label == option_text) {
options = optgroups[i].innerHTML;
}
}
return options;
};
});