NeoSketo NeoSketo - 4 months ago 16
Javascript Question

How to auto select users state in data-bind options select in Knockout

i have a drop down of states and their 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 is a variable that may or maynot contain the users info. By default its null. But if the user has already logged in then it should populate with the users selected state. For this example, the users has logged in and their select state is 9 for florida.

so i declared usersState = 9; at the top.

What i am trying to do is simply auto select Florida in the drop down based on the users info.

not sure why its not selecting it. Here is my fiddle: http://jsfiddle.net/neosketo/sw9dzjk1/2/

Answer

The SelectedState refers to a state object. Your initial selection is a number. You'll have to find the state object corresponding to the number:

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>

(Note that I used Array.prototype.find which isn't supported by all browsers)

Alternatively, you could use the optionsValue option to tell knockout to use the value property to match selection to options. Personally, I prefer using the actual object: knockout being able to work with references to real instances rather than using strings makes developing easier.

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>