rui_sonika
rui_sonika

Reputation: 45

one select controls another select

Hello I want to achieve this:

I have select 1 and select 2 with same options values and when I select option of select 1 then automatically select 2 changes the selected value for the same as select 1.

This is my code, but doesn't work...any help? please.

function changeYear() {

    // select 1
    var x = document.getElementById("sel1");
    var year= x.options[x.selectedIndex].value;

    //select 2
    var y = document.getElementById("ctl00_conteudo_ano_anomBox1");
    var phc= y.options[y.selectedIndex].value;

    //result
    year = phc;
}
<!-- i want to control sel2 with sel1 -->

<select id='sel1' class='form-control' onchange='changeYear()'>
      <option value='2019'>2020</option>
      <option value='2018'>2019</option>
</select>

<select id="sel2" class='form-control'>
			<option selected="selected" value="2019">2019</option>
			<option value="2018">2018</option>
			<option value="2017">2017</option>
			<option value="2016">2016</option>
			<option value="2015">2015</option>
			<option value="2014">2014</option>
			<option value="2013">2013</option>
</select>

Upvotes: 0

Views: 388

Answers (1)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

You just need to set the .value property of the second select:

function changeYear() {

  // select 1
  var x = document.getElementById("sel1");
  var year= x.options[x.selectedIndex].value;

  //select 2
  document.getElementById("sel2").value = year;
}
<!-- i want to control sel2 with sel1 -->

<select id='sel1' class='form-control' onchange='changeYear()'>
  <option selected="selected" value="2019">2019</option>
  <option value="2018">2018</option>
  <option value="2017">2017</option>
  <option value="2016">2016</option>
  <option value="2015">2015</option>
  <option value="2014">2014</option>
  <option value="2013">2013</option>
</select>

<select id="sel2" class='form-control'>
  <option selected="selected" value="2019">2019</option>
  <option value="2018">2018</option>
  <option value="2017">2017</option>
  <option value="2016">2016</option>
  <option value="2015">2015</option>
  <option value="2014">2014</option>
  <option value="2013">2013</option>
</select>

Upvotes: 1

Related Questions