KRob
KRob

Reputation: 389

Knockoutjs not updating UI when programmatically updating an observable

Why is the dropdown not updating when I programmatically update the observable and open the modal? Here is all the code https://jsfiddle.net/krob636/jes9bvLw/119/

Changing the observable updates the dropdown if I try changing the element's value first. Click Launch modal button then click the Observable button. The selected id changes but not the dropdown. Now click the Element button, then click Observable button again. The dropdown does change.

Javascript

this.selectedSimulators = ko.observableArray().extend({notify: 'always'});

this.simulators = ko.observableArray([
  new Simulator(1, 1, 1, "CH-53E", "APT", "APT 2F190-2"),
  new Simulator(2, 1, 1, "CH-53E", "EAET", "EAET 2H164-2"),
  new Simulator(3, 1, 1, "CH-53E", "WST", "WST 2F174-2")
]);

this.openModal = function() {
  $('#exampleModal').modal('show');
  this.selectedSimulators(1);

  // UI does not update without calling this 
 //$("#ddSims").val(1);
}

HTML

  <select class="form-control" id="ddSims" multiple="multiple" data-bind="options: simulators,
      optionsText: 'typeAndSerialNumber',
      optionsValue: 'id',
      selectedOptions: selectedSimulators,
      multiselect: {includeSelectAllOption: true}">
 </select>

 <button type="button" class="btn btn-primary" data-bind="event: {click: openModal}">
    Launch modal
  </button>

Upvotes: 1

Views: 309

Answers (1)

Jason Spake
Jason Spake

Reputation: 4304

You're mixing observables and observableArrays. selectedSimulators is an array, but then you're setting it to a value of 1 instead of pushing a value of 1 to the array. Try self.selectedSimulators.push(1); instead.

Upvotes: 0

Related Questions