my goal is for radio buttons to change an <option> of a <select> element (drop-down list).
I was already able to solve the reverse behavior (selecting another <option> results in a change in a radio button). As you can see here:
function validate()
{
var x = document.getElementById("location_select");
var y = x.options[x.selectedIndex].value;
{
document.getElementById(y).checked = true;
}
}
<select id="location_select" onchange="validate()">
<option value="berlin">Berlin</option>
<option value="paris">Paris</option>
</select>
<label>
<input type="radio" id="berlin" name="location">
<span>Berlin</span>
</label>
<label>
<input type="radio" id="paris" name="location">
<span>Paris</span>
</label>
Now I would like to generate the reverse behavior.
Desired Behavior: Changing the radio button also changes the <option> in my selection.
The radio button ID is the same as the "value" of my drop-down options. So a JS variable can then be used for the ID as well as the "value".
Basically, this is my progress currently:
function validate_2()
{
{
document.getElementById("location_select").selectedIndex = "1";
}
}
<label>
<input type="radio" id="berlin" name="location" onchange="validate_2()">
<span class="title">Berlin</span>
</label>
<label>
<input type="radio" id="paris" name="location" onchange="validate_2()">
<span class="title">Paris</span>
</label>
<select id="location_select">
<option value="berlin">Berlin</option>
<option value="paris">Paris</option>
</select>
I'm open to better methods if this isn't a good one.
This function can change selected option of
<select>by changingradioinputsGet the
idof the radio input which was changed and setvalueattribute of<select>tagVersion 1
Version 2
It can be shortened to
Version 3
Using
selectedIndexexplicitly