javascript - Knockout select and textbox sharing binding -
i have page select , input-box being bound same value. idea 1 select value select, however, user should able enter arbitrary string in input-box. problem if enter not present in select, because of binding, value set first item in select.
this behavior want achieve:
user selects value select
- value set selected item.
- input updated selected value.
user enters text in input
- value set entered text.
- select not change unless value present in collection of available values.
in other words, want last changed control valid value. want both controls date as long given value valid control.
my code looks this:
js
var viewmodel = { value: ko.observable('1'), set: ['1', '2', '3'] }; ko.applybindings(viewmodel);
html
<!-- ko if: set.length > 1 || (set.length > 0 && set[0] != '') --> <select type="text" class="form-control input-small" data-bind="options: set, value: value"> </select> <!-- /ko --> <input class="form-control input-small" data-bind="value: value" style="margin-top: 5px;" />
here jsfiddle showing how code works: http://jsfiddle.net/b2rwg/
[edit]
i've found working solution (http://jsfiddle.net/b2rwg/2/), it's not pretty, , there has better way solve problem.
as can see add inputvalue observable bound text input. add computed named virtualset contains both original items , new item (from text input). susbcribe inputvalue select automatically set when typing.
var viewmodel = { inputvalue: ko.observable('1'), value: ko.observable('1'), set: ['1', '2', '3'] }; viewmodel.virtualset = ko.computed({ read: function () { var vs = this.set.slice(0); if (this.inputvalue() && this.inputvalue().length) vs.unshift(this.inputvalue()); return vs; }, owner: viewmodel }); viewmodel.inputvalue.subscribe(function (value) { viewmodel.value(value); });
i hope helps.
Comments
Post a Comment