I have some dropdown menus in javascript, as well as an array that holds all of them:
HTML:
<select name="a"> <option value="ABC">ABC</option> <option value="DEF">DEF</option> <option value="GHI">GHI</option> </select> <select name="b"> <option value="JKL">JKL</option> <option value="MNO">MNO</option> <option value="PQR">PQR</option> </select> Javascript:
var a_dropdown = document.getElementById("a") var b_dropdown = document.getElementById("b") var c_dropdown = document.getElementById("c") var all_dropdowns = [a_dropdown, b_dropdown, c_dropdown] Now, I can set the value of a dropdown from its standalone variable, and it visually updates just fine:
a_dropdown.value = a_dropdown.options[2].value This can be seen working in this jsfiddle.
Now, this is where things get weird. I can also change the value of the dropdown by the array index of the array that holds all the dropdowns:
all_dropdowns[0][all_dropdowns[0].selectedIndex].value = all_dropdowns[0].options[2].value; which updates the selected value in the same way. However, while this updated value is reflected in the selected index value of a_dropdown, as shown in this updated jsfiddle (run and look at the alert message), the changed value isn't shown visually in the dropdown menu.
Seeing as javascript passes variables by reference for non-primitive types, I can't figure out why setting the value of the dropdowns in these two different ways would result in different behaviors. Ideally, I'd like to figure out a way to get the second method of setting the dropdown value to result in the same behavior as the first (actually visually changing the menu's value).
1 Answer
In the second example (all_dropdowns[0][all_dropdowns[0].selectedIndex].value = all_dropdowns[0].options[2].value;), you're not actually setting the value of the Select.
You're setting the value of the option.
In the fiddle, when you log it, you also log the value of the option, which is of course GHI.
See this updated fiddle and watch the JS on line 6 and 7 to see the difference.