Vileps
Vileps

Reputation: 31

Get the id of the selected value in combobox with Knockout

I want to get the Id of the selected index in my combobox in knockout is it possible ?

<select id="lstEntreprisesCbx" data-bind="options:Entreprises,
                        optionsText: 'NomEntreprise',
                        optionsCaption: '-- Nouvelle Entreprise --'">
</select>

Thanks

Upvotes: 3

Views: 3642

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

You could use the selectedIndex property of the select element to find out the currently selected option.

If you wanted to put this in a binding handler, you could something like:

ko.bindingHandlers.selectedIndex = {
    init: function(element, valueAccessor) {
        ko.utils.registerEventHandler(element, "change", function() {
             var value = valueAccessor();
            if (ko.isWriteableObservable(value)) {
               value(element.selectedIndex);   
            }
        });
    }
};

This assumes that you are binding it against an observable (if you want to bind against a non-observable, then it takes a little more code) and you would use it like:

<select id="lstEntreprisesCbx" data-bind="options:Entreprises,
                        optionsText: 'NomEntreprise',
                        optionsCaption: '-- Nouvelle Entreprise --',
                        selectedIndex: myIndex">
</select>

Here is a sample: http://jsfiddle.net/rniemeyer/K6SZQ/

update

I had read the question as specifically wanting the selectedIndex of the currently selected value, which may have been wrong. If you really want to get something like an id of the currently selected object, then you can use the value binding along with the optionsValue option. It would look like:

<select id="lstEntreprisesCbx" data-bind="options:Entreprises,
                        optionsText: 'NomEntreprise',
                        optionsCaption: '-- Nouvelle Entreprise --',
                        value: selectedId,
                        optionsValue: 'id'">
</select>

So, you specify which value to update in the value binding and which property to use (as a string) in the optionsValue binding. If you omit optionsValue, then it will populate your value with the entire object. This is also what you would use if your options array was just primitive values.

Sample: http://jsfiddle.net/rniemeyer/3LyLs/

Upvotes: 3

Related Questions