Solution 1 :

Firstly, your selector is not ideal if you have multiple <select> elements on the page. You’d be better to use #maschAusw.

You have to specify the selected attribute. You can do something like this:

$("#maschAusw").children('option[value="opt2"]').prop('selected', true);

You should also remove the selected attribute from the currently selected option, which can be done as follows:

$("#maschAusw").children('option[value="opt2"]')
               .prop('selected', true)
               .siblings()
               .prop('selected', false);

Please see the working example below:

const data = ['opt1', 'opt2', 'opt3'];

for (let i = 0; i < data.length; i++) {
  console.log(data[i]);
  $('#maschAusw').append($("<option>").attr('value', data[i]).text(data[i]));
}


$("#maschAusw").children('option[value="opt2"]')
               .prop('selected', true)
               .siblings()
               .prop('selected', false);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="maschAusw">
  <option selected disabled value="">Choose...</option>
</select>

Problem :

How do I select a dynamicaly created option with jquery?

I have created a dynamic dropdown-menu with jquery. The options are filled by the “data” array.

After the options have been created I try so select a specific option by query. In my example ‘opt2’.

In this example everything works well. But in my application always the first option will be selected. Only if I create an alert() before the $("select").val('opt2'); then the correct option is selected.

I think it is because the select options where created dynamicaly and they are not ready when I try to select it.

const data = ['opt1', 'opt2', 'opt3'];

for (let i = 0; i < data.length; i++) {
  console.log(data[i]);
  $('#maschAusw').append($("<option>").attr('value', data[i]).text(data[i]));
}


$("select").val('opt2');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select id="maschAusw">
  <option selected disabled value="">Choose...</option>
</select>

Comments

Comment posted by CompanyDroneFromSector7G

Won’t that have the same problem though?

Comment posted by BenM

@CompanyDroneFromSector7G no, did you actually run the snippet?

Comment posted by CompanyDroneFromSector7G

No I actually didn’t which is why I actually asked the question. Actually.

Comment posted by BenM

@CompanyDroneFromSector7G try it, you might be surprised.

Comment posted by CompanyDroneFromSector7G

😉 Actually, they both behave the same, but to be fair that could be my browser…

By