Search code examples
javascriptjqueryknockout.jsknockout-2.0

How to get selected value from drop down list using knockout


So i am using knockout and trying to get the selected item's id in my javascript on the change event. Here is my html

 <div id="platforms" data-bind="with: platformsViewModel">
            <p>
                Selected Platform:
                <select data-bind="options: platforms, optionsText: 'displayName', value: 'id', optionsCaption: 'Choose...', event: { change: loadMedias }" ></select>
            </p>
        </div>

my view model is as follows

my.viewModels.PlatformsViewModel = function () {
    var self = this;

    self.platforms = ko.observableArray();
    self.message = ko.observable();

    self.loadMedias = function (data, event) {
        my.loadMedias(data.id);
    }
}

What am i missing here?


Solution

  • It looks like this may be a simple fix, where you're possibly using the value binding where you should be using the optionsValue binding:

    <select data-bind="options: platforms, optionsText: 'displayName', optionsValue: 'id', optionsCaption: 'Choose...', event: { change: loadMedias }" ></select>
                                                                  <!-- ^ here -->
    

    However, why not put the logic in the view model, rather than in your view:

    my.viewModels.PlatformsViewModel = function () {
        var self = this;
    
        self.platforms = ko.observableArray();
        self.message = ko.observable();
    
        //new observable to hold selected platform
        self.selectedPlatform = ko.observable();
        //subscribe to changes in the observable value to trigger the loading
        self.selectedPlatform.subscribe(function(newValue) {
            my.loadMedias(newValue.id);
        });
    }
    

    And an updated <select> that will bind the actual platform object selected, rather than just its ID:

    <select data-bind="options: platforms, optionsText: 'displayName', value: selectedPlatform, optionsCaption: 'Choose...'" ></select>