Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Based on your comments, I think I now know what you're trying to do. I am going to abstract it so that it is easier to follow as your ViewModel and Objects are very complex and not easy to understand without explanation.</p> <p>If you have object types, <code>Book</code> and <code>Author</code> with constructors:</p> <pre><code>function Book(data) { this.ISBN = ko.observable( data.ISBN ); this.Title = ko.observable( data.Title ); this.AuthorID = ko.observable( data.AuthorID ); /* other properties */ } function Author(data) { this.AuthorID = ko.observable( data.AuthorID ); this.Name = ko.observable( data.Name ); /* other properties */ } </code></pre> <p>To select a Book from a <code>select</code> box and have a <code>input</code> display bound to the Authors name, you will need the viewmodel:</p> <pre><code>var vm = {}; vm.books = ko.observableArray( /* initial data */ ); vm.authors = ko.observableArray( /* initial data */ ); vm.selectedBook = ko.observable(null); vm.selectedBooksAuthor = ko.computed( function() { var authors = vm.authors(), selectedBook = vm.selectedBook(); if( !selectedBook ) return null; // cannot get .AuthorID() if selectedBook == null var id = selectedBook.AuthorID(); for( var a in authors ) { if( authors[a].AuthorID() == id ) return authors[a]; } }) </code></pre> <p>And your HTML:</p> <pre><code>&lt;select data-bind="options: books, optionsText: 'Title', optionsCaption: 'Select a book...', value: selectedBook"&gt;&lt;/select&gt; &lt;!-- ko with: selectedBooksAuthor --&gt; &lt;input type="text" data-bind="value: Name" /&gt; &lt;!-- /ko --&gt; </code></pre> <p>Please note, this can get pretty inefficient over large sets of data -- look into using a better search algorithm (rather than the 'linear' used here) for your <code>computed observable</code> i.e. <code>selectedBooksAuthor</code></p> <p><strong>EDIT:</strong></p> <p>Please see <a href="http://jsfiddle.net/CkNf6/" rel="nofollow">this fiddle</a> for a working demonstration.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload