enable a disabled select when choose a value in another select tag

french_dev picture french_dev · Jun 16, 2015 · Viewed 21.1k times · Source

I have these two select tag:

<select>
  <option value="car">car</option>
  <option value="truck">truck</option>
  <option value="moto">moto</option>
  <option value="none">none</option>
</select>

<select disabled>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

As you can see, my second select have the disabled attribute. I would like in javascript, when I selected the option "car" in my first select, the second select with the car's choice become enabled to make a choice.

How can I proceed in javascript?

Answer

Praveen Kumar Purushothaman picture Praveen Kumar Purushothaman · Jun 16, 2015

JavaScript Version:

document.getElementById("one").onchange = function () {
  document.getElementById("two").setAttribute("disabled", "disabled");
  if (this.value == 'car')
    document.getElementById("two").removeAttribute("disabled");
};
<select id="one">
  <option value="car">car</option>
  <option value="truck">truck</option>
  <option value="moto">moto</option>
  <option value="none">none</option>
</select>

<select disabled id="two">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

jQuery Version:

$('#one').change(function() {
  $('#two').prop('disabled', true);
  if ($(this).val() == 'car') {
    $('#two').prop('disabled', false);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select id="one">
  <option value="car">car</option>
  <option value="truck">truck</option>
  <option value="moto">moto</option>
  <option value="none">none</option>
</select>

<select id="two" disabled>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>