Knockout.groupedOptions
with jQuery Mobile
by Semmel
HTML
<script src="http://knockoutjs.com/downloads/knockout-3.2.0.debug.js"></script>
<script src="https://rawgithub.com/Supertext/knockout.groupedOptions/master/knockout-groupedOptions.min.js"></script>
<select data-bind="groupedOptions: { groups: { coll: Groups }, optionsCaption: '- Please select -', value: SelectedOption }"></select>
<span data-bind="visible: SelectedOption(), text: SelectedText"></span>
<br/>
<select data-bind="value: groupedValue, options: availableCountries, optionsText: 'countryName', optionsValue:'code', optionsCaption:'Select a destination'" data-native-menu="false">
</select>
<select data-native-menu="false" id="plainSelect">
<option>Please..</option>
<option value="A">First<i class="ui-btn ui-nodisc-icon ui-icon-bars ui-btn-icon-notext ui-btn-inline ui-alt-icon"></i></option>
<option value="B">Second</option>
</select>
<br/>
<i class="ui-btn ui-nodisc-icon ui-icon-bars ui-btn-icon-notext ui-btn-inline ui-alt-icon">sad asd</i>
<a href="#" class="ui-btn ui-shadow ui-corner-all ui-icon-check ui-btn-icon-notext ui-btn-b ui-btn-inline ui-nodisc-icon">Check</a>
<input type="text" data-bind="value: doubleText" /><br/>
<input type="text" data-bind="value: doubleText" />
CSS
body
{
margin: 15px;
}
JavaScript
// this is the data for our view-model, and which we'll render inside the <select> element
var demoGroups = [{
"Label": "group 1",
"Options": [{
"Text": "item 1 - 1",
"Value": "1-1"
},
{
"Text": "item 1 - 2",
"Value": "1-2"
},
{
"Text": "item 1 - 3",
"Value": "1-3"
}]
},
{
"Label": "group 2",
"Options": [{
"Text": "item 2 - 1",
"Value": "2-1"
},
{
"Text": "item 2 - 2",
"Value": "2-2"
},
{
"Text": "item 2 - 3",
"Value": "2-3"
}]
}];
var vmMain = function(groups) {
var self = this;
self.groupedValue = ko.observable();
self.doubleText = ko.observable("Double!");
self.availableCountries= ko.observableArray([
{ countryName: 'France', code: "F" },
{ countryName: 'Germany', code: "D" },
{ countryName: 'Spain', code: "E" }
]);
// This is the outermost collection which is bound to the <select> element.
// This must always be stated in the 'data-bind' declaration.
self.Groups = ko.observableArray();
// This property holds the selected item from the options list
self.SelectedOption = ko.observable();
self.SelectedText = ko.computed(function() {
if (self.SelectedOption()) {
return "You selected \"" + self.SelectedOption().Text() + "\"";
}
return "";
});
if (typeof(groups) !== "undefined" && groups) {
for (var i = 0, iMax = groups.length; i < iMax; i++) {
self.Groups.push(new vmGroup(groups[i]));
}
}
}
// a view-model to represent an <optgroup> element
var vmGroup = function(group) {
var self = this;
// This is the text which appears inside each <optgroup> element, using the element's 'label' attribute.
// This property uses the conventional name and consquently may be omitted in the 'data-bind'...