O'Reilly logo

KnockoutJS Web Development by John Farrar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Select binding

Our first example of using Knockout with a select element will be for single item selection. This is the markup where we will put colors into the options:

<p>
  Colors: ( <span data-bind="text: colors"></span> )
  <br/>
  <select data-bind="options: colorOptions, 
              value: colors,
              optionsCaption: 'Choose a color'"></select>
</p>

In our code we will be doing one more special thing at this time. After we create the ViewModel we will modify one of its attributes and add another color to the colorOptions array using the push function, common to JavaScript. This means that some parts of JavaScript are great already and we should continue to use them. Here is the script code:

<script> function MyModel(){ this.colorOptions = ko.observableArray(['Red','Green','Blue','Yellow','Green']); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required