Knockout.js Select bindings

Knockout.js is versatile in how you can bind to HTML SELECT inputs. Most of the examples show bindings to simple arrays, but there is a lot more functionality available. The tricky part is knowing where to look. You might think to look for a select binding, but you actually want to look at the documentation for the options binding.

Let me show you an example. Instead of having a simple array of single values to bind to, you want to have an array of objects.

var invlist = [{"id":"PGT_MUM-A","desc":"Decorative pot red mum","combodesc":"A - Decorative pot red mum","price":"25.00","altid":"A"},
{"id":"PGT_MUM-B","desc":"Refill pot red mum","combodesc":"B - Refill pot red mum","price":"20.00","altid":"B"},
{"id":"PGT_MUM-C","desc":"Decorative pot white mum","combodesc":"C - Decorative pot white mum","price":"25.00","altid":"C"},
{"id":"PGT_MUM-D","desc":"Refill pot white mum","combodesc":"D - Refill pot white mum","price":"20.00","altid":"D"}];

In this example, we have inventory items that have an id, description, price and some additional fields. Here is the way the HTML SELECT would look:

<select id="zSaleItem" data-bind="value:currItem, options:invlist, optionsValue:'id', optionsText:'combodesc', optionsCaption:'Item Number'"></select>

In the data-bind, we still specify the value which ties to the field in the viewmodel that this input field is bound to. The rest of the data-binding creates all of the options to be in the select. The first field is “options” which links the array holding all the options to be used to populate the select. In this example, it is “invlist” which is the sample array shown above. The next field is “optionsValue”. This tells the binding what property of the object in the array to place in the value mapped to the viewmodel after a selection is made. “optionsText” specifies the property to be displayed as the text value of the option in the select. When there is not a value selected, you use “optionsCaption” to specify what to display. In this case, it is “Item Number”. Other examples could be “Choose”, “Select”, etc.

I have found this gives a lot of flexibility in defining how you want the SELECT to display and function.

Leave a Reply

Your email address will not be published. Required fields are marked *