Search code examples
jqueryappendhtml-selectselected

after appending options to select box, selected is not honored


I've seen a lot of other questions about using jQuery to dynamically append options to a select box, and I'm follow their instructions but it's still not selecting the option. Here's the HTML:

<select id="updated-value-dropdown" class="form-control" style="min-width: 10em;">
</select>

And here's the Javascript:

$('#edit-modal').on('show.bs.modal', function (e) {
  target_element = $(this).find('#updated-value-dropdown');
  target_element.html(''); // clear options
  var add_options = getOptionsToAdd();
  for (var i = 0; i < add_options.length; i++) {
    target_element.append(new Option(add_options[i], add_options[i], i === 0, i === 0));
  }
}

The result is a drop-down box with the correct options, and I can see when I inspect the page that the first option is marked as "selected" in the HTML as it should be, but it still isn't show up as being actually selected when the modal is shown... why isn't this working?

This is what the dropdown looks like on the page (without having clicked it):

Without clicking

This is what the dropdown looks like when I click on it -- as you can see, the first option is "selected" with a check mark next to it, but as you can see in the image above, it's not actually appearing as the value in the actual box (unless I manually click the value):

With clicking

Also, I'm using bootstrap, I don't know if that has anything to do with it...


Solution

  • Oh god I'm an idiot -- there was another place in the code that was calling target_element.val(...) and setting it to a value which wasn't one of the options in the options list, so that was clearing the value I was trying to select.