2016-07-25 15 views
0

我有一個下降的狀態下和他們的ID:中如何自動數據綁定選項中選擇用戶狀態來選擇淘汰賽

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

的Javascript

function ViewModel() { 
    this.States = ko.observableArray(states); 
    this.SelectedState = ko.observable(usersState); 
}; 


var states = [ 
     { value: 10, text: "California" }, 
     { value: 3, text: "New York" }, 
     { value: 9, text: "Florida" } 
    ]; 




ko.applyBindings(new ViewModel()); 

usersState是一個變量,可能或不可能包含用戶信息。默認情況下它是空的。但是,如果用戶已經登錄,那麼它應該填充用戶選擇的狀態。在這個例子中,用戶已經登錄,佛羅里達州的選擇狀態是9。

所以我宣佈usersState = 9;在頂部。

我想要做的只是自動選擇佛羅里達在下拉根據用戶的信息。

不知道爲什麼它沒有選擇它。這裏是我的小提琴:http://jsfiddle.net/neosketo/sw9dzjk1/2/

回答

0

SelectedState指狀態對象。您的初始選擇是號碼。你必須找到對應的數量的狀態對象:(我用Array.prototype.find注意這是不是所有的瀏覽器都支持)

var usersState = 9; 
 

 
// This method finds an object by value property 
 
var findStateById = function(states, id) { 
 
    return states.find(function(state) { 
 
    return state.value === id; 
 
    }); 
 
}; 
 

 
function ViewModel() { 
 
    this.States = ko.observableArray(states); 
 
    
 
    // In this example, SelectedState is an object with a value and text property 
 
    this.SelectedState = ko.observable(findStateById(states, usersState)); 
 
}; 
 

 
// Test data 
 
var states = [{ 
 
    value: 10, 
 
    text: "California" 
 
}, { 
 
    value: 3, 
 
    text: "New York" 
 
}, { 
 
    value: 9, 
 
    text: "Florida" 
 
}]; 
 

 
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> 
 
<select data-bind="options: States, optionsText: 'text', value: SelectedState"></select>

或者,你可以使用optionsValue選項告訴淘汰賽使用value屬性將選擇與選項匹配。就個人而言,我更喜歡使用實際的對象:淘汰賽能夠引用實際實例而不是使用字符串,這使得開發更容易。

var usersState = 9; 
 

 

 
function ViewModel() { 
 
    this.States = ko.observableArray(states); 
 

 
    // In this example, SelectedState is a number 
 
    this.SelectedState = ko.observable(usersState); 
 
}; 
 

 
var states = [{ 
 
    value: 10, 
 
    text: "California" 
 
}, { 
 
    value: 3, 
 
    text: "New York" 
 
}, { 
 
    value: 9, 
 
    text: "Florida" 
 
}]; 
 

 

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

 
<select data-bind="options: States, 
 
        optionsText: 'text', 
 
        optionsValue: 'value', 
 
        value: SelectedState"></select>