I'm using knockout js and the chosen plugin (https://github.com/harvesthq/chosen) to try and make a good looking multi select.
I've tried various ways but can't get the multiselect to work with the data I'm using. When I click on the multiselect, no values are shown even though the options binding contains the correct data.
HTML:
<select multiple="multiple" data-bind="options: allCustomers,
selectedOptions: event().customers, optionsText: 'name',
optionsValue: 'id', chosen: true " ></select>
Simplified version of the view model:
function Event()
{
this.customers = ko.observableArray();
};
//for chosen plugin
ko.bindingHandlers.chosen = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).chosen();
}
}
function ViewModel()
{
this.event = ko.observable(new Event());
this.allCustomers = ko.observableArray();
};
var viewModel = new ViewModel();
$.getJSON("/get_json", function(data)
{
for (var c = 0; c < data.customers.length; c++)
{
viewModel.allCustomers.push(data.customers[c]);
}
});
ko.applyBindings(viewModel);
PHP:
function get_json()
{
$eventData = array(
'customers' => array(array('name' => 'Bob', 'id' => 1), array('name' => 'John', 'id' => 2)),
'moreData' => array(),
'evenMoreData' => array()
);
echo json_encode($eventData);
}
This shows the chosen styled select box but when I click in it, no options appear.
When I create a local JS array in the view model for the customers and pass that into allCustomers, the multiselect works correctly (see my jsfiddle) so it's something to do with getting data from the server, but I've been staring at this a while and can't see the problem!
Any help much appreciated