I have several
<select>
elements on my php/html page. One of them is populated using JavaScript as below:
for (let i = 0; i < heritages.data.id.length; i ) {
$('#heritage').append(new Option(heritages.data.name[i], heritages.data.id[i]));
}
However, when I then try and force the select to change it's currently selected item, it doesn't do anything.
$("#heritage option:selected").attr("selected", null);
$("#heritage option[value='" heritage_id "']").attr("selected", "selected");
The same code works with selects that have been explicitly populated in HTML rather than in JavaScript. Therefore it is not a problem with the above code as such, but something is going wrong when being added in JavaScript. The heritage_id variable definitely has the correct value of 28 and the four options that are added have values of 27, 28, 29 and 30.
CodePudding user response:
Make sure your second snippet (the one with the attr
s) only gets executed after the first snippet is run.
For example, if the first snippet is executed in the callback of an async operation, your second snippet would not be selecting any elements. Thus the commands have no effect.
This is the most probable cause, because otherwise your code should work, as the demo below shows.
const heritages = {
data: {
id: [27, 28, 29, 30],
name: [27, 28, 29, 30],
}
}
for (let i = 0; i < heritages.data.id.length; i ) {
$('#heritage').append(new Option(heritages.data.name[i], heritages.data.id[i]));
}
const heritage_id = 28;
$("#heritage option:selected").attr("selected", null);
$("#heritage option[value='" heritage_id "']").attr("selected", "selected");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="heritage">
<option value="z">z</option>
<option value="w" selected>w</option>
</select>