Philip Loyer
Philip Loyer

Reputation: 768

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?

Upvotes: 2

Views: 2260

Answers (2)

C.Fasolin
C.Fasolin

Reputation: 319

Html:

<select name="ddlUsers" id="ddlUsers" class="form-control"
                            data-bind="options: ViewModel.CashierPage.AvailableCash,  optionsText: 'OptionTextInfo', value: ViewModel.CashierPage.CashSelected, optionsCaption: 'Cassa...'"></select>

in js:

 public CashSelected: KnockoutObservable();
...
 self.CashSelected = ko.observable(null);
 self.CashSelected.subscribe(function(valueNewValue){/*your code*/});

Upvotes: -1

James Thorpe
James Thorpe

Reputation: 32202

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>

Upvotes: 5

Related Questions