Reputation: 57
Good day,
I've got an onchange function for a select tag that looks like this:
function dropdown() {
var x = document.getElementById("mySelect").value;
document.getElementById("demoA").innerHTML = "" + x;
}
<select id="mySelect" onchange="dropdown()">
<option value="Value A1">Value B1</option>
<option value="Value A2">Value B2</option>
</select>
<span id="demoA">Value A</span>
<span id="demoB">Value B</span>
My goal is, that depending on the selected option it would not only change the Value A in the demoA span, but also the Value B in demoB span - for example with the displayed option name (Value B1 or Value B2).
Can someone help me out with this one? If the values between the option tags can't be retrieved, is there an alternative solution which would give the same result?
Upvotes: 0
Views: 423
Reputation: 174
You can get a reference to the currently selected option from the dropdown and access its text value via the .text
property.
function dropdown() {
var x = document.getElementById("mySelect");
var val = x.value;
var txt = x.options[x.selectedIndex].text;
document.getElementById("demoA").innerHTML = "" + val;
document.getElementById("demoB").innerHTML = txt;
}
<select id="mySelect" onchange="dropdown()">
<option value="Value A1">Value B1</option>
<option value="Value A2">Value B2</option>
</select>
<span id="demoA">Value A</span>
<span id="demoB">Value B</span>
Upvotes: 1