javascripthtmlradio-buttonhtml-selectselectedindex

How can a radio button change an <option> of a drop-down list in JS?


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>
As you can see, it's only static so far.
I'm open to better methods if this isn't a good one.


Solution

  • This function can change selected option of <select> by changing radio inputs

    Get the id of the radio input which was changed and set value attribute of <select> tag

    Version 1

    function validate_2() {
        checkedVal = event.target.id;
        locationSelect = document.getElementById("location_select");
            
        locationSelect.value = checkedVal;
    }
    

    Version 2

    It can be shortened to

    function validate_2() {
        // ID becomes variable in JS
        location_select.value = event.target.id;
    }
    

    Version 3

    Using selectedIndex explicitly

    function validate_2() {
        checkedVal = event.target.id;
        locationSelect = document.getElementById("location_select"); 
        indexToSelect = Array.from(locationSelect.options).findIndex(opt => opt.value == checkedVal);
        locationSelect.selectedIndex = indexToSelect;
    }