Knockout option Binding

On Load of select element, change the option to the specific one

by Vikash Kumar Gupta

HTML

<div>
  <span data-bind="text: welcome"></span>
  
  <div>
    <h5>
      Select list, changing the option runtime
    </h5>
    <label for="selectOnRunTime" >Selecion on runtime</label>
    <select id="selectOnRunTime" data-bind="foreach: myStates, event:{change: console.log('Current Data selected')}, value:defaultSelection" title="Selction on Runtime">
      <!-- ko if:$index()===0 -->
        <option data-bind="text: 'Select', value: -1"></option>
      <!-- /ko -->
      <option data-bind="text: $data, value: $index"></option>
    </select>
    
    <div>
      <label>My Choice of State:</label>
      <input type="text" data-bind="value: defaultSelection"/>
      <span data-bind="text: defaultSelection"></span>
    </div>
  </div>
</div>

JavaScript

var ViewModel = function(){
	var self= this;
  self.welcome = ko.observable("Hi, Welcome to Knockout handson !!!");
 self.defaultSelection = ko.observable(-1); 
  self.myStates= ko.observableArray(["Delhi","Punjab", "Jharkhand","Karnataka","Mumbai"]);
  
}

ko.applyBindings(new ViewModel());