Could someone please show me how to preselect all items in a knockout data-bound select with multiple selection tag set?
I've tried using this code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript" src="js/knockout-2.0.0.debug.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta charset="utf-8" http-equiv="X-UA-Compatible" content="IE=9" />
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE" />
</head>
<body>
Choose a company: <select id="companies" data-role="select" data-bind="options: companies,
optionsCaption: 'Choose...',
optionsText: 'companyName',
optionsValue: 'companyValue',
selectedOptions: chosencompanies" data-native-menu="false" multiple></select>
<input data-bind="value: chosencompanies"></input>
<script type="text/javascript">
$(document).ready(function () {
function company(name, value) {
this.name = ko.observable(name);
this.value = ko.observable(value);
}
var viewModel = {
companies: ko.observableArray([
{ companyName: "test", companyValue: 0 },
{ companyName: "test1", companyValue: 1 },
{ companyName: "test2", companyValue: 2 },
{ companyName: "test5", companyValue: 5 },
{ companyName: "test7", companyValue: 7 },
]),
chosencompanies: ko.observableArray(),
resetcompanies: function () { this.chosencompanies(null) }
};
ko.applyBindings(viewModel);
$("#companies option").prop('selected', true);
$("#companies").selectmenu();
$("#companies").selectmenu('refresh', 'true');
});
</script>
</body>
</html>
Even though I'm using $("#companies option").prop('selected', true) it seems to only affect the visual appearance of the dropdown control and not the data-bound chosenCompanies varialbe which is what I need set? :(whose value you can see also since it is data-bound to the input field beneath the dropdown) And before someone proposes please, I realize that I could initialize the observableArray with a comma separated value list, but what when my selection options are dynamic and I don't know with what values I should preinit the observableArray?
TIA