简体   繁体   中英

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>

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM