So i have a select2 tag input working fine, displaying the tags correctly, and storing the selected id into the selectedProducts observableArray. However, my HTTPPost is expecting an array of objects, and not an array of integers. I've been looking to see how I can have the select2 save as an object (i.e. {id: 1, text: "abc"}) instead of just an array of integers.
My binding is below:
<div class="col-sm-10">
<input type="hidden" id="tags" class="select2 form-control" multiple="multiple" data-bind="value: selectedProducts, select2: {tags: ko.toJS($parent.availableProducts), placeholder: 'select products'}" />
<pre data-bind="text: ko.toJSON(products, null, 2)"></pre>
</div>
var newItem = function (newitem) {
var self = this;
self.id = ko.observable();
self.selectedProducts = ko.observableArray();
self.products = ko.computed(function () {
return self.selectedProducts().split(',');
}, self);
}
var viewModel = function (data) {
var self = this;
self.newitem= ko.observable(new newItem());
self.availableProducts = ko.observableArray([]);
$.ajax({
type: "GET",
url: '/GetAllProducts',
dataType: 'json',
contentType: "application/json; charset=utf-8",
async: false,
success: function (data) {
ko.mapping.fromJS(data, {}, self.availableProducts);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
}
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindingsAccessor) {
var obj = valueAccessor(),
allBindings = allBindingsAccessor(),
lookupKey = allBindings.lookupKey;
setTimeout(function () {
$(element).select2(obj);
}, 0);
if (lookupKey) {
var value = ko.utils.unwrapObservable(allBindings.value);
$(element).select2('data', ko.utils.arrayFirst(obj.data.results, function (item) {
return item[lookupKey] === value;
}));
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).select2('destroy');
});
},
update: function (element) {
$(element).trigger('change');
}
}