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']); this.colors = ko.observableArray(); }; myModel...