I am creating a select
dropdown on the fly using PHP to get the data and build the options. Then I am using Ajax to fetch this (with the following lines) and prepend an additional option.
All of this works as intended, my only issue is that in the dropdown it always selects the second option which is the first one from my PHP / Ajax call but not the option that I am prepending before that.
I also tried changing selected
to selected='selected'
but that doesnt make a difference.
What am I doing wrong here or how this can be changed in jQuery / JS so that it selects the prepended option ?
Note: I am using this inside a Bootstrap 3 modal.
My JS (shortened):
var levelMain = $(this).closest('tr').find('.levelMain').text();
// ...
$.ajax({
url: 'ajax.php?node=fetchNav1',
cache: false,
error:function(err) {
alert(err.statusText);
},
success:function(html) {
$('#divLevelMain').html(html);
$("#levelMain").prepend("<option value='' selected>" + levelMain + "</option>");
}
});
The Select is a standard HTML select that looks as follows:
<select class="form-control" id="levelMain">
<option value="some value">some text</option>
// ...
</select>
It should be pretty easy to update the selectedIndex
of the <select>
element with the following:
success:function(html) {
$('#divLevelMain').html(html);
$("#levelMain").prepend("<option value=''>" + levelMain + "</option>");
$("#levelMain")[0].selectedIndex = 0;
}