I feel like I'm missing something very basic, but I can't get a dropdown menu to work as I expect using Knockout.js.
I have a set of objects I want to present in a menu, and I need to find the selected option and post that to the server. I can get the menu to render, but can't seem to get the value of the selected item. My view model looks like this:
function ProjectFilterItem( name, id ) {
this.Name = name;
this.Id = id;
}
function FilterViewModel() {
this.projectFilters = ko.observableArray([
new ProjectFilterItem( "foo", "1" ),
new ProjectFilterItem( "bar", "2" ),
new ProjectFilterItem( "baz", "3" )
]);
this.selectedProject = ko.observable();
}
ko.applyBindings( new FilterViewModel() );
and my view markup looks like this:
<select
id = "projectMenu"
name = "projectMenu"
data-bind = "
options: projectFilters,
optionsText: 'Name', /* I have to enquote the value or I get a JS error */
optionsValue: 'Id', /* If I put 'selectedProject here, nothing is echoed in the span below */
optionsCaption: '-- Select Project --'
"
></select>
<b>Selected Project:</b> <span data-bind="text: selectedProject"></span>
How do get the selected menu item to display in the span, and to post to the server? (I assume the observable I render in the span is the same one I'd post.) Do I need another property in the ProjectFilterItem
, like this.selected = ko.observable(false);
? If so, how would I declare it as the target of the value?