2

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>
user-44651
  • 3,924
  • 6
  • 41
  • 87

1 Answers1

1

Attribute selected is a part of <option>, not <select> itself. You should modify your code as:

function update_animal_options(optionsArray) {
    $(animals_select).empty();

    $(animals_select).append(
        '<option value=' + optionsArray[i] 
        + (optionsArray[i] == current_selected? ' selected' : '') + '>' 
        + optionsArray[i] + '</option>'
    );
}

ALso, it's always a good idea to wrap attribute values in quotes. Otherwise code like value=Some value here will not be treated as you expect.

u_mulder
  • 54,101
  • 5
  • 48
  • 64