I am running through a list of items in an array. Outputting those options to via JQuery to a html SELECT
.
I want to compare the current item in the array to a previously selected variable and set the <option>
attribute to selected
.
But it fails to add the attribute.
What am I doing wrong?
//PHP
$myAnimalArray = some filled array();
$s_current_selected = "Zebra";
//SOME HTML FORM
<select class="form-control" id="animals_select" name="animals_select"></select>
JQuery
<script type="text/javascript">
$(document).ready(function () {
let animal_array = <?php echo json_encode($myAnimalArray); ?>;
let animals_select = document.getElementById("animals_select");
let current_selected = "<?php echo $s_current_selected; ?>";
update_animal_options(animal_array);
function update_animal_options(optionsArray) {
$(animals_select).empty(); //remove any prior entries
for (let i = 0; i < optionsArray.length; i++) {
$(animals_select).append('<option value=' + optionsArray[i] + '>' + optionsArray[i] + '</option>');
// HERE IS WHERE MY PROBLEM IS
if (optionsArray[i] == current_selected) {
$(animals_select).attr('selected', 'selected');
}
}
}
});
</script>