on Change event in select with knockout

岁酱吖の 提交于 2020-01-03 11:03:07

问题


I have a problem how to call onchanges knock js to my select option, i already have a function and html, but when i choose the select option, nothing changes

<select data-bind="event:{change:setSelectedStation() },
                   options: seedData,
                   optionsText: 'text',
                   optionsValue: 'value'">
</select>

here is my function

setSelectedStation: function(element, KioskId){
     this.getPopUp().closeModal();
     $('.selected-station').html(element);
     $('[name="popstation_detail"]').val(element);
     $('[name="popstation_address"]').val(KioskId);

     $('[name="popstation_text"]').val(element);
     // console.log($('[name="popstation_text"]').val());
     this.isSelectedStationVisible(true);
},

回答1:


Use knockout's two-way data-binds instead of manually subscribing to UI events.

Knockout's value data-bind listens to UI changes and automatically keeps track of the latest value for you.

Instead of replacing HTML via jQuery methods, you use text, attr and other value bindings to update the UI whenever your selection changes.

If you want to perform additional work when a selection changes (e.g. closing a pop up), you subscribe to the selected value.

var VM = function() {
  this.seedData = [
    { 
      text: "Item 1",
      data: "Some other stuff"
    },
    { 
      text: "Item 2",
      data: "Something else"
    },
    { 
      text: "Item 3",
      data: "Another thing"
    }
  ];
  
  this.selectedItem = ko.observable();
  
  this.selectedItem.subscribe(function(latest) {
    console.log("Input changed");
  }, this);
};

ko.applyBindings(new VM());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>

<select data-bind="
        value: selectedItem,
        options: seedData,
        optionsText: 'text'">
</select>

<!-- ko with: selectedItem -->
<p>
  Your selection: <span data-bind="text: data"></span>
</p>
<!-- /ko -->


来源:https://stackoverflow.com/questions/43157905/on-change-event-in-select-with-knockout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!