I’m new to JavaScript.
I have 2 key and value pairs they are ids:
myselect->myoption
myselect2->myoption2
Code:
function checkboxStatusChanges() {
var multiselect = document.getElementById("myselect");
var multiselectOption = multiselect.getElementsByTagName('option')[0];
var values = [];
var checkboxes = document.getElementById("myoption");
var checkedCheckboxes = checkboxes.querySelectorAll('input[type=checkbox]:checked');
for (const item of checkedCheckboxes) {
var checkboxValue = item.getAttribute('value');
values.push(checkboxValue);
}
var dropdownValue = "Nothing is selected";
if (values.length > 0) {
dropdownValue = values.join(', ');
}
multiselectOption.innerText = dropdownValue;
}
The code already used 1 of the pair values myselect->myoption document.getElementById("myselect") ,my question is ,how to code a loop inside the code ,so that both of the 2 pair values can be used in the code ?
2
Answers
You can use an array of objects to solve this. Define your pair value inside
object.selectId
andobject.optionId
and do forEach to apply the function for those objects like this:It is my understanding that your function is absolutely fine as is, except that you want to parameterize
"myselect"
and"myoption"
askey
andvalue
. So, you can do that at the function level. Parameterization is a fundamental feature of functions in JavaScript and, easy peasy:Now you just need to call this function twice, once with each
key
,value
pair.In the simplest form you can now do:
If you need a single function that does both those things because it’s an event handler or something, then that’s also very easy to solve:
And now that we’ve gotten all that out of the way, if you really insist on doing so, you could use a loop: