achref achref - 5 months ago 19
HTML Question

Knockout: How to select an item by property name from an observableArray of objects

I am making my first steps with knockout by developing a small app that prints the information about a selected person, the problem is that I don't know exactly how to select an object from the array according to a specific property.

In my fiddle, I need to print all the information about a person that I select but also the persons names doesn't appear in the select box, it shows

[Object Object]


What am I missing to get the results I want?



var people = [{
name: "Contact 1",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail@me.com",
type: "family"
}, {
name: "Contact 2",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail@me.com",
type: "friend"
}, {
name: "Contact 3",
address: "1, a street, a town, a city, AB12 3CD",
tel: "0123456789",
email: "anemail@me.com",
type: "friend"
}];

function ContactsViewModel(people) {
var self = this;
self.contacts = ko.observableArray(people);
}

ko.applyBindings(new ContactsViewModel(people));

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div>
Show me:
<select data-bind="options: contacts"></select>
</div>
<div>
Name: <span databind="text: name"></span><br>
Adress: <span data-bind="text: address"></span><br>
Tel: <span data-bind="text: tel"></span><br>
Email: <span data-bind="text: email"></span><br>
Type: <span data-bind="text: type"></span><br>
</div>





My fiddle: http://jsfiddle.net/VxT5Y/146/

Answer

Use select optionsText data-bind property:

 <select data-bind="options: contacts,
                   optionsText: 'name',
                   value: selectedName,
                   optionsCaption: 'Choose...'"></select>