Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get selected menu option from a knockout.js observableArray?

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?

like image 397
Val Avatar asked Nov 05 '12 21:11

Val


1 Answers

You just need use with the value binding to bind the selected value:

From the options documentation:

Note: For a multi-select list, to set which of the options are selected, or to read which of the options are selected, use the selectedOptions binding. For a single-select list, you can also read and write the selected option using the value binding.

In your example:

<select 
    id        = "projectMenu"   
    name      = "projectMenu"
    data-bind = "
        value: selectedProject,
        options:        projectFilters,
        optionsText:    'Name',
        optionsValue:   'Id',
        optionsCaption: '-- Select Project --'
    "
></select>

See Demo.

like image 181
nemesv Avatar answered Nov 03 '22 19:11

nemesv