【问题标题】:Knockoutjs clear selected value in comboboxKnockoutjs 清除组合框中的选定值
【发布时间】:2011-12-29 13:10:40
【问题描述】:

我有这个简单的 knockout.js 应用程序:

查看:

<select data-bind="options: allDocumentTypes , optionsCaption: 'Choose ...', optionsValue: 'id', optionsText: 'name', selectedOptions: selectedDocument"></select>
<span data-bind="click: cl">CLEAR VALUE!</span>

还有这个简单的 ViewModel:

function documentType(id, name){
    this.id = id;
    this.name = name;
}

var viewModel = {
    allDocumentTypes: ko.observableArray([]),
    selectedDocument: ko.observable(''),
    cl: function(){
       viewModel.selectedDocument('');
    }
};

/* load data */
viewModel.allDocumentTypes.push(new documentType(1,'Test 1'));
viewModel.allDocumentTypes.push(new documentType(2,'Test 2'));
ko.applyBindings(viewModel);

我希望,在我点击跨度“CLEAR VALUE!”后,在选择中将选择选项“选择...”,但它没有发生。 viewModel 中的值设置为“”(空字符串),这是正确的,但用户仍然在 select 中看到旧值。

有没有办法做到这一点?

感谢您的帮助:)

【问题讨论】:

    标签: javascript mvvm knockout.js


    【解决方案1】:

    您必须将绑定类型更改为“value”而不是“selectedOptions”。下一步是在 cl 函数中设置 viewModel.selectedDocument:

    viewModel.selectedDocument(null);
    

    【讨论】:

      【解决方案2】:

      在某些情况下,将 observable 值设置为 null 将不起作用,例如:

      // This is the array
      self.timePeriods = ko.observableArray([
          new timePeriod("weekly", 7),
          new timePeriod("fortnightly", 14),
          new timePeriod("monthly", 30),
          new timePeriod("half yearly", 180),
          new timePeriod("yearly", 365)
      ]);
      

      下面是HTML部分:

      <select data-bind="options: timePeriods, 
                                  optionsText: function(item) { 
                                     return item.Name;
                                  }, 
                                  value: selectedPeriod"
                                  class="combo">
      

      您无法通过以下方式重置选择框:

      self.selectedPeriod(null); // but this will not work
      

      Insetead 写这个:

      self.selectedPeriod(self.timePeriods()[0]);
      

      【讨论】:

        【解决方案3】:
        <script>
        var vm ={ 
        CountryId=ko.observable(),
        QC=ko.observable(),
        clearSelectedStation: function () {
        this.CountryId(null);   //DropDown
        this.QC('');   //Textbox
        }
        };
        </script>
        

        这是一个html

         <input type="text" tabindex="10" data-bind="value:QC"/>
        
        <select class="dropdownlist" data-bind="options:Countries, value: CountryId, 
        optionsCaption: '--Select--', optionsText: 'CountryName', optionsValue: 'CountryId'">
        

        【讨论】:

          猜你喜欢
          • 2012-09-23
          • 2020-11-22
          • 2012-08-21
          • 1970-01-01
          • 1970-01-01
          • 2011-12-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多