Pregunta

I am currently working on an application that has a select box with option groups associated to each item. Essentially, the end goal would be a 'select box' equivalent of the following:

Buyers (optgroup)


  • Jenny (option)
  • Johnny (option)

Sellers (optgroup)


  • Megan (option)
  • Matthew (option)

My current code is partially working. It creates the groups successfully. If I use a span inside the option instead of data-binding directly, it produces a blank record for each item. However, it will not show the option text and it will stop running if I try to bind it directly to the option.

Could you review my code and give me an idea of what might be causing the issue?

Here is a fiddle with my current code: http://jsfiddle.net/lkritchey/my3Kw/6/

Below is a copy of my JavaScript code and HTML:

JavaScript:

var UserGroup = function (group, users) {
    this.GroupName = group;
    this.Users = users;
};

var User = function (guid, fullName) {
    this.UserId = guid;
    this.FullName = fullName;
};

var userListViewModel = {
    groupList: ko.observableArray([]),
    singleUserList: ko.observableArray([])
};

function populateData() {
    var users1 = [new User(1, "Jenny"), new User(2, "Johnny")];
    var users2 = [new User(3, "Megan"), new User(4, "Matthew")];
    userListViewModel.groupList.push(
    new UserGroup("Buyers", users1));
    userListViewModel.groupList.push(
    new UserGroup("Sellers", users2));
}
populateData();
ko.applyBindings(userListViewModel);

HTML:

<div>
     <h2>List of users:</h2>

    <div data-bind="foreach: $root.groupList">
         <h4 data-bind="text: GroupName"></h4>

        <ul data-bind="foreach: Users">
            <li data-bind="text: UserId + '-' + FullName"></li>
        </ul>
    </div>
</div>
<div>
    <h2>Select a User</h2>
User:
    <select data-bind="foreach: $root.groupList">
        <optGroup data-bind="attr: {label: GroupName}, 
        foreach: User">
            <option> <span data-bind="text: FullName"></span>

            </option>
        </optGroup>
    </select>
</div>
<div>
     <h2>Select a User:</h2>
User:
    <select data-bind="foreach: $root.groupList">
        <optGroup data-bind="attr: {label: GroupName}, 
        foreach: User">
            <option data-bind="text: FullName, value: UserId"></option>
        </optGroup>
    </select>
</div>
¿Fue útil?

Solución

You have to change User to Users in:

<optGroup data-bind="attr: {label: GroupName}, foreach: Users">

Also, you have to realize that an <option> element cannot contain any other elements. You'll have to remain with:

<option data-bind="text: FullName, value: UserId"></option>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top