2012-09-04 68 views
1

我的收音機應該在初始化時選擇(第一次加載然後用戶可以改變選擇),但是第一次沒有選擇收音機,如何適當地初始化「選擇」?收音機沒有選擇,如何設置「選中」?

這裏收音機「Two」應該選擇爲「selected」爲true?

@using (Html.BeginForm("Index", "Two", FormMethod.Post, new Dictionary<string, object> { { "data-bind", "submit:onSubmit" } })) 
{ 

<table> 
    <tr> 
     <td> 
      <div data-bind="foreach: items"> 
       <input type="radio" name="items" data-bind="attr: { value: id }, checked: $root.selected" /> 
       <span data-bind="text: name"></span> 
      </div> 
      <div data-bind="text: selected"> 
      </div> 
     </td> 
    </tr> 
</table> 

<input type="submit" name="send" value="Send" /> 
} 

<script type="text/javascript"> 
var viewModel = { 
    items: [ 
    { "id": 1, "name": "one", "selected": false }, 
    { "id": 2, "name": "two", "selected": true }, 
    { "id": 3, "name": "three", "selected": false } 
], 
selected: ko.observable(), 

    onSubmit: function(){ 

     var x = this.selected(); 

     } 
    }; 

$(function() { 
     ko.applyBindings(viewModel); 
    }); 

</script> 

回答

0

你需要設置你的頂級selected可觀察到是true值的id

類似:

$(function() { 
    var selected = ko.utils.arrayFirst(viewModel.items, function(item) { 
     return item.selected; 
    }); 

    if (selected) { 
     viewModel.selected(selected.id); 
    } 

    ko.applyBindings(viewModel); 
}); 

樣品:http://jsfiddle.net/rniemeyer/rbsZC/