Robin Robin - 5 months ago 34
Javascript Question

KnockOutJS Show Hide elements on dropdown selection change

Hi I am trying to get selected value of dropdown in Knockout js so that I can hide/ show other elements based on selection. Below is what I have tried.
What is happening that I am able to get right value on button click but not on dropdown selection change.

Below is my code. The button gives right value, but dropdown selection change event gives previous value & not the selected one.

JS

function ViewModel() {
var self = this;
self.optionValues= ko.observableArray(["Test1", "Test2", "Test3"]);
self.selectedValue = ko.observable();

self.save = function() {
alert(self.selectedValue());
}
}

ko.applyBindings(new ViewModel());


HTML

<select data-bind="event:{ change: save},options: optionValues, value: selectedValue"></select>

<button data-bind="click: save">Save</button>

Answer

Instead of the change event binding binding, you should subscribe directly on your selectedValue observable, and call your logic from there:

function ViewModel() {
  var self = this;
  self.optionValues = ko.observableArray(["Test1", "Test2", "Test3"]);
  self.selectedValue = ko.observable();
  self.selectedValue.subscribe(function(newValue) {
    self.save();
  });
  self.save = function() {
    alert(self.selectedValue());
  }
}
ko.applyBindings(new ViewModel());

Html:

<select data-bind="options: optionValues, value: selectedValue"></select>

<button data-bind="click: save">Save</button>

Demo JSFiddle.