使用Knockout获取组合框中所选值的id

时间:2013-04-21 21:46:48

标签: knockout.js

我想在淘汰赛的组合框中获取所选索引的ID是否可能?

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

由于

1 个答案:

答案 0 :(得分:3)

您可以使用select元素的selectedIndex属性来查找当前选定的选项。

如果你想把它放在一个绑定处理程序中,你可以这样:

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

这假定您将它绑定到一个observable(如果你想绑定一个不可观察的,那么它需要更多的代码),你会像以下一样使用它:

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

以下是一个示例:http://jsfiddle.net/rniemeyer/K6SZQ/

更新

我已经阅读了这个问题,特别想要当前所选值的selectedIndex,这可能是错误的。如果您确实希望获得当前所选对象的id之类的内容,则可以使用value绑定以及optionsValue选项。它看起来像是:

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

因此,您指定要在value绑定中更新哪个值以及在optionsValue绑定中使用哪个属性(作为字符串)。如果省略optionsValue,则会使用整个对象填充value。如果您的选项数组只是原始值,那么这也是您将使用的。

示例:http://jsfiddle.net/rniemeyer/3LyLs/

相关问题