user2872856 user2872856 - 25 days ago 8
HTML Question

Autoselect HTML hidden option value based on previous option

I have 2 select tags which come with the same option, male and female. One of the

select
, "age" is hidden.

<select name="gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>

<select name="age" style="display:none;">
<option value="12">Male</option>
<option value="18">Female</option>
</select>


When user select "male" in "gender", I wish the "age" will automatically select "male" as well. I expect the same thing as "female". How to achieve this through javascript?

Answer

You can attach an event change to your select gender and set the value of age on every change.

Note that both elements should be loaded with a default selected value for case that the end user do not select nothing and also check that it is better to move inline styling style="display:none;" to a separated css file.

Code:

var gender = document.getElementsByName('gender')[0],
    age = document.getElementsByName('age')[0];

gender.addEventListener('change', function() {
  age.value = (gender.value == 1) ? 12 : 18;

  console.log('Gender:', gender.value);
  console.log('Age:', age.value);
});
<select name="gender">
  <option value="1">Male</option>
  <option value="2">Female</option>
</select>

<select name="age" style="display:none;">
  <option value="12">Male</option>
  <option value="18">Female</option>
</select>