Ask A Question

Notifications

You’re not receiving notifications from this thread.

Dynamic Dropdown without JQuery

Herbert Schmoll asked in Javascript

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;
};

Reply

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;
};
});

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 87,400+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.