javascript - How to auto select users state in data-bind options select in Knockout -
i have drop down of states , 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 variable may or maynot contain users info. default null. if user has logged in should populate users selected state. example, users has logged in , select state 9 florida.
so declared usersstate = 9; @ top.
what trying auto select florida in drop down based on users info.
not sure why not selecting it. here fiddle: http://jsfiddle.net/neosketo/sw9dzjk1/2/
the selectedstate
refers state object. initial selection number. you'll have find state object corresponding number:
var usersstate = 9; // method finds object value property var findstatebyid = function(states, id) { return states.find(function(state) { return state.value === id; }); }; function viewmodel() { this.states = ko.observablearray(states); // in example, selectedstate object value , 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>
(note used array.prototype.find
isn't supported browsers)
alternatively, use optionsvalue
option tell knockout use value
property match selection options. personally, prefer using actual object: knockout being able work references real instances rather using strings makes developing easier.
var usersstate = 9; function viewmodel() { this.states = ko.observablearray(states); // in example, selectedstate 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>
Comments
Post a Comment