【问题标题】:How to get the selected value from the list of dropdown using Knockout如何使用 Knockout 从下拉列表中获取所选值
【发布时间】:2013-03-06 18:27:57
【问题描述】:

这是视图模型

 self.choiceSelect = ko.observable();
            self.selectedItems = ko.observableArray([]);
            self.selectedComponent = ko.observable();
            self.componentList = ko.observableArray();

 self.GetData = function () {

            $.ajax({
                url: self.url + "GetComponent",
                type: "GET",
                cache: false
            })
            .fail(function (qxhr, status, errorThrown) {

            })
            .done(function (data) {

                self.componentList(data);

            });

        };

这是代码:

<select id="report-Components" data-bind="value: selectedComponent, options: componentList, optionsText: 'componentName'"></select><br /><br />
<h4>Component Attributes</h4>
<!-- ko if: selectedComponent  -->
<!-- ko if: selectedComponent().componentField  -->
<div data-bind="foreach: selectedComponent().componentField">
    <div class="control-group">
        <div class="controls">
            <input type="checkbox" data-bind="checked: $parent.selectedItems, value: $data" />
        </div>
        <label class="control-label">
            <strong data-bind="text: fieldText"></strong>
        </label>
    </div>                                    
</div>
<!-- /ko -->                            
<!-- /ko -->
<!-- ko if: selectedItems  -->
<div data-bind="foreach: selectedItems">
    <!-- ko if: fieldChoice.length > 0  -->
    <label data-bind="text: fieldText"></label>
    <select data-bind="options: fieldChoice, optionsText: 'choiceName', value: $data.choiceSelect"></select>
    <!-- /ko -->
    <!-- ko if: fieldChoice.length == 0  -->
    <label data-bind="text: fieldText"></label>
    <input type="text" value=""/>
    <!-- /ko -->
</div>  
<!-- /ko -->  

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    您需要将选择值绑定到可观察对象:

    <select data-bind="options: fieldChoice, optionsText: 'choiceName', value: $data.nameOfObservable">
    

    这应该会在选择更改时更新 nameOfObservable。

    这个 observable 需要位于您正在查看的数组中的每个项目上。因此,无论您在 selectedItems 中存储什么对象,它们都需要具有同名的 observable 属性。

    要让视图模型中的所有内容都可观察,我建议使用mapping plugin

    self.componentList = ko.mapping.fromJS(data);
    

    并对视图模型上的其他属性执行相同操作。

    【讨论】:

    • 但是在这里我使用 foreach 创建了多个下拉列表,如果我与 observable 绑定,它不起作用
    • 好吧,你必须将每个选择绑定到不同的 observable,但是你为什么不这样做呢?只需为每个选择绑定一个单独的 observable。
    • 但我不知道页面上应该出现多少下拉菜单。它将基于 observableArray。
    • 是的,但是您在 selectedItems 上有一个 foreach 循环,因此该循环中的每个对象都需要具有绑定到下拉列表的可观察属性。我已经更新了代码以使其更加明确。
    • 以及我需要在哪里定义这个 observable
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-25
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 2013-02-25
    • 2014-01-08
    相关资源
    最近更新 更多