Reputation: 9269
I have implemented a grouped select box in knockout.js which was inspired by ( I figured it out by looking at ) KnockoutJS - Binding value of select with optgroup and javascript objects by RP Niemeyer but it's a little different. it looks like this.
<select name="Field" data-bind="foreach: FieldList.Groups, value:Field" >
<optgroup data-bind="attr: {label: Label}, foreach: Children">
<option data-bind="text: Text, value: Value"></option>
</optgroup>
</select>
my viewmodel would look like
var viewmodel = {
Field: 2,
Groups:{
Label:"Field 1",
Children:[
{ Text:"Field1", Value:1 },
{ Text:"Field2", Value:2 }
]
}
Something like that, in any case it works great. However, I really need to put a "Please Select ..." as the first option.
Given that it's a foreach loop
a) optionsCaption binding doesn't work and
b) I can't just add the option in there cuz it would be repeated for each group.
just to make sure no one can help me i'll add this constraint. I am actually code gen'ing ( just some C# on server ) the html and while I can do a lot of custom stuff I can't add arbitrary pieces of text, ie comments into the output. which is to say I can't do the containerless foreach because I can only emmit htmltags not html comments.
ugg.
If anyone has any idea's please let me know I would greatly appreciate it. thanks, R
Upvotes: 1
Views: 2848
Reputation: 9269
Alrighty, so I decided to just do my own binding. It was much easier then I expected. I will post it here. I just ripped this straight from the source code and modified it slightly. The changes are really quite simple, I strongly suggest you compare the two to see what I"m doing. Now, there are some caveats.
a) I have basically hardcoded some "conventions" for my own convenience and because I wasn't sure quite how to make it generic enough for any type model. Basically you should look at the viewmodel I"m using and if you can't/don't want to reproduce something similar you will probably have to change the code to reflect that. but it's dead simple (with firebug :) )
b) It is updating the model's selected value for a single select but I have not tried this using multiple select. I'm using something else for multiple select. But I left that code in from the original "options" binding.
---update---
figured out c. it works to update the viewmodel.
----end update ---
c) I'm not sure if it will update the select if you change the model. Frankly I was testing that when I realized I couldn't seem to make it update the select options on a regular select box so I'm a bit stymied on that. I'll update when/if I figure it out.
d) you must include the ensureDropdownSelectionIsConsistentWithModelValue function because it's a "private" function in ko and you can't reach it from out side.
function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
if (preferModelValue) {
if (modelValue !== ko.selectExtensions.readValue(element))
ko.selectExtensions.writeValue(element, modelValue);
}
// No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
// If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
// change the model value to match the dropdown.
if (modelValue !== ko.selectExtensions.readValue(element))
ko.utils.triggerEvent(element, "change");
}
ko.bindingHandlers['groupedSelect'] = {
'update': function (element, valueAccessor, allBindingsAccessor) {
if (ko.utils.tagNameLower(element) !== "select")
throw new Error("options binding applies only to SELECT elements");
var selectWasPreviouslyEmpty = element.length == 0;
var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
}), function (node) {
return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
});
var previousScrollTop = element.scrollTop;
var value = ko.utils.unwrapObservable(valueAccessor());
value = value.groups();
var selectedValue = element.value;
// Remove all existing <option>s.
// Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
while (element.length > 0) {
ko.cleanNode(element.options[0]);
element.remove(0);
}
if (value) {
var allBindings = allBindingsAccessor();
if (typeof value.length != "number")
value = [value];
if (allBindings['optionsCaption']) {
var option = document.createElement("option");
ko.utils.setHtml(option, allBindings['optionsCaption']);
ko.selectExtensions.writeValue(option, undefined);
element.appendChild(option);
}
for (var a= 0, b = value.length; a < b; a++) {
var optGroup = document.createElement("optgroup");
ko.bindingHandlers['attr'].update(optGroup, ko.observable({label: value[a].label()}));
var children = ko.utils.unwrapObservable(value[a].children());
for (c=0, d=children.length; c<d; c++){
var option = document.createElement("option");
// Apply a value to the option element
var optionValue = typeof allBindings['optionsValue'] == "string" ? value[a].children()[c][allBindings['optionsValue']] : value[a].children()[c];
optionValue = ko.utils.unwrapObservable(optionValue);
ko.selectExtensions.writeValue(option, optionValue);
// Apply some text to the option element
var optionsTextValue = allBindings['optionsText'];
var optionText;
if (typeof optionsTextValue == "function")
optionText = optionsTextValue(value[a].children()[c]); // Given a function; run it against the data value
else if (typeof optionsTextValue == "string")
optionText = value[a].children()[c][optionsTextValue]; // Given a string; treat it as a property name on the data value
else
optionText = optionValue; // Given no optionsText arg; use the data value itself
if ((optionText === null) || (optionText === undefined))
optionText = "";
ko.utils.setTextContent(option, optionText);
optGroup.appendChild(option);
}
element.appendChild(optGroup);
}
// IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
// That's why we first added them without selection. Now it's time to set the selection.
var newOptions = element.getElementsByTagName("option");
var countSelectionsRetained = 0;
for (var i = 0, j = newOptions.length; i < j; i++) {
if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
ko.utils.setOptionNodeSelectionState(newOptions[i], true);
countSelectionsRetained++;
}
}
element.scrollTop = previousScrollTop;
if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
// Ensure consistency between model value and selected option.
// If the dropdown is being populated for the first time here (or was otherwise previously empty),
// the dropdown selection state is meaningless, so we preserve the model value.
ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.unwrapObservable(allBindings['value']), /* preferModelValue */ true);
}
// Workaround for IE9 bug
ko.utils.ensureSelectElementIsRenderedCorrectly(element);
}
}
Usage
<select data-bind="groupedSelect:FieldList,optionsText:'Text',optionsValue:'Value',optionsCaption:'-- Please Select --',value:FieldEntityId">
Viewmodel
"FieldList":{
"groups":[
{"label":"SomeGroup1","children":[
{"Text":"field1","Value":"1"},
{"Text":"field2","Value":"2"}
]},
{"label":"SomeGroup 2","children":[
{"Text":"field3","Value":"3"},
{"Text":"field4","Value":"4"}
]}
]
}
I guess if you have any questions or comments let me know.
Also let me explain why there model looks, well, kind of strange. I am really just serializing from C# model that looks like this
public class GroupSelectViewModel
{
public GroupSelectViewModel()
{
groups = new List<SelectGroup>();
}
public List<SelectGroup> groups { get; set; }
}
public class SelectGroup
{
public string label { get; set; }
public IEnumerable<SelectListItem> children { get; set; }
}
SelecListItem is a c# class which uses pascal notation.
Upvotes: 4