I am having the following select
in my html:
<select class="form-control" data-bind="multiSelectCommaSeparated: CityIds, options: $root.Cities, optionsText: 'CityName', optionsValue: 'CityId', valueUpdate: 'change'" multiple="true"></select>
I am trying to write a knockout custom binding to update the CityIds
observable with comma separated values whenever user selects multiple cities in the multi select drop down. For example if I have the following select
:
<select id="cities" multiple="multiple">
<option value="1">City 1</option>
<option value="2">City 2</option>
<option value="3">City 3</option>
<option value="4">City 4</option>
</select>
and the user selects first 3 cities, then my observable should have 1,2,3
. If the user de-selects City 3
, then the observable should have 1,2
and this should happen as soon soon as the user selects/de-selects any value in the select
.
I have written the following custom binding by using reference from this question:
ko.bindingHandlers.multiSelectCommaSeparated = {
init: function (element, valueAccessor) {
var selMulti = $.map($(element.id + " option:selected"), function (el, i) {
return $(el).text();
});
valueAccessor(selMulti);
},
update: function (element, valueAccessor) {
var selMulti = $.map($(element.id + " option:selected"), function (el, i) {
return $(el).text();
});
valueAccessor(selMulti);
}
}
In the above custom binding, the update event is not firing when I change my selection in the multi select dropdown
. What should I change in the custom binding to achieve my requirement?