Reputation: 31
I have an object that has a school list with nested classes and nested students in each class
What i need is to bind the optionsText to show the hierarchy so that the dropdown menu shows the options just like :
School A has
Student 1
Student 2
School B has
Student 4
Student 5
Student 6
I am able to get the name of the school on the dropdown but the student part which i am able to get with a foreach on the classes shows as 'undefined' with the binding below.
<select data-bind="options: SchoolList, optionsText: function (item) { return item.School + '|' + item.Classes.forEach(function (item) { return item.Student})}, optionsValue: 'Id', value:SchoolListId, optionsCaption: 'Select'" id="school" name="school" class="school"></select>
Any help will be appretiated,
Upvotes: 0
Views: 156
Reputation: 12587
To me, it sounds like you're trying to solve too many things with one dropdown. Perhaps this is more a UX problem than anything. Also, to my knowledge, you cannot invoke that kind of logic in the optionsText
binding (and why would you?).
What I believe you need is a two step form, OR, a wizard of sorts.
I'll try and "pseudo"-code option 1 below:
function Student(){
var self = this;
//the properties
};
function School(name, students){
var self = this;
self.name = ko.observable();
self.students = ko.observableArray();
if(name)
self.name(name);
if(students)
self.students(students);
};
function ViewModel(){
var self = this;
self.schools = ko.observableArray(
new School('A', [
new Student(),
new Student(),
]),
new School('A', [
new Student(),
new Student(),
new Student(),
]),
);
};
And the markup:
<select data-bind="options: schools, value: selectedSchool, valueAllowUnset: false"></select>
<!-- ko if: students().length > 0 -->
<select data-bind="options: students, value: selectedStudent, valueAllowUnset: false"></select>
<!-- /ko -->
Upvotes: 0