在下拉列表中设置默认值

时间:2014-11-17 10:13:26

标签: javascript knockout.js

我有两个可以操作的下拉菜单。第二次下降; httpauthmode由第一个下拉列表中的值操纵; httprestype。

我希望第二次下降; httpauthmode在用户选择时更改为默认值 httpreqtype()== 2;即

      <option value="0" selected="selected">None</option>
      //I want the value = 0 be the default value

的Javascript

  _self.httpreqtype = ko.observable( httpreqtype );
  _self.httpauthmode = ko.observable(null);

这是我的HTML

  <label>HTTP Request Type</label><br/>
    <select data-bind="value: httpreqtype" style="width:200px">
    <?php 
        foreach($httpRequestOptions as $key=>$val) {
            echo '<option value="'.$val["id"].'" >'.$val["name"].'</option>';
        };
    ?>
    //$httpRequestOptions is an array inside my viewModel, I only put a piece of my code
    </select>

    <label>HTTP Auth Type</label><br />
    <select data-bind="value: httpauthmode" style="width:200px">
        <option value="0" selected="selected">None</option>
        <option value="1">Basic Authentication</option>
        <option value="2" data-bind = "visible: httpreqtype() == 2" >Body Encryption</option>
        <option value="3" data-bind = "visible: httpreqtype() == 2" >Basic Authentication + Body Encryption</option>
    </select>

我尝试使用谷歌搜索并尝试了订阅功能,将observable设置为(null),(&#34;&#34;)以及许多其他方式。有人可以帮助我,或者建议我可以尝试哪种方法。非常感谢它,并提前多多感谢。

2 个答案:

答案 0 :(得分:1)

你应该采用非常不同的方法。仔细阅读options binding documentation并尝试将代码重新编写为该方法。基本上,它允许您对select标记进行数据绑定,并使Knockout动态呈现option

这样的事情:

&#13;
&#13;
var Model = function(httpreqtype){
  var _self = this;
  _self.httpauthmode = ko.observable(null);
  _self.httpreqtype = ko.observable( httpreqtype );
  _self.httpauthmode = ko.observable(null);
  
  var mode0 = { id: 0, txt: "None" };
  var mode1 = { id: 1, txt: "Basic Authentication" };
  var mode2 = { id: 2, txt: "Body Encryption" };
  var mode3 = { id: 3, txt: "Basic Authentication" };
    
  _self.availableHttpAuthModes = ko.computed(function() {
    if (_self.httpreqtype() == 2) {
      return [mode0, mode1];
    }
    return [mode0, mode1, mode2, mode3];
  });
}

ko.applyBindings(new Model(2));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<select data-bind="value: httpauthmode, 
                   optionsText: 'txt',
                   options: availableHttpAuthModes" >
</select>
<br /><br />Change httpreqtype:
<br /><input data-bind="value: httpreqtype, valueUpdate: 'afterkeydown'" />
&#13;
&#13;
&#13;

答案 1 :(得分:0)

httpauthmode更改为'0'时,将None设置为httprestype '2' 的值):

_self.httprestype.subscribe(function(value) {
    if(value === '2') {
        _self.httpauthmode('0');
    }
});

JSFiddle