Reputation: 391
I have multiple select drowdowns on my page, and I have put the same onchange function to all the select menus like so:
<select onchange="myResultsFunction()">
<option></option>
<option></option>
</select>
Whenever the selected value of any of the select dropdowns change, then it must display an updated list of values in a specific div like so:
<div id="selected-results">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
So, I need some help with the actual function, because I don't know how to go from here. My function starts off by getting the ID of the div where I want the unordered list of results to show. But how do I go from here? Because I assume I need to output it using a loop or something in order for me to create a list of results? And how do I actually grab the selected value in the dropdowns?
function myResultsFunction() {
document.getElementByID("selected-results");
}
Upvotes: 0
Views: 80
Reputation: 6532
var selects = document.querySelectorAll("select.custom_component_option_select");
// get all selelct elements with class .custom_component_option_select
var list = document.querySelector("#selected-results > ul");
//get list, ul element
selects.forEach(select => {
//for each select element
select.addEventListener('change', event => {
// add event Listener change
myResultsFunction()
// on change call function
})
})
function myResultsFunction() {
list.innerHTML = "";
// on change empty the list
selects.forEach(select => {
// for each select
if ((select.options[select.selectedIndex].text !== "...") === true) {
// if selcted value is not ... , feel free to edit his
var li = document.createElement("li");
// creat new li
li.innerHTML = select.options[select.selectedIndex].text;
// add value to it
list.appendChild(li);
// add to list
}
})
}
<select class="custom_component_option_select">
<option selected value="test">...</option>
<option value="test">1-1</option>
<option value="test">1-2</option>
</select>
<select class="custom_component_option_select">
<option selected value="test">...</option>
<option value="test">2-1</option>
<option value="test">2-2</option>
</select>
<select class="custom_component_option_select">
<option selected>...</option>
<option value="test">3-1</option>
<option value="test">3-2</option>
</select>
<div id="selected-results">
<ul>
</ul>
</div>
Upvotes: 2