繁体   English   中英

使用Knockout.js如何从数组中的多选下拉列表中提取所选项目

[英]Using Knockout.js how to extract selected items from a multiselect dropdown list in an array

当这些元素嵌入表行中时,是否可以从多选Select HTML元素中提取选定的项目?

请检查jsFiddle

使用Knockout.js时,如何为每一行列出选定的国家/地区ID? 如何为每一行使用selectedValues选项?

<div id="CountryList" style="margin-top:40px; margin-bottom:40px">
    <table id="Countries">
        <thead>
            <tr>
                <th>Line No.</th>
                <th>Country</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: countryLines">
            <tr>
                <td data-bind="text: lineNumber"></td>
                <td>
                    <select data-bind="options: $root.availableCountries, optionsValue: 'countryId', optionsText: 'countryName'" multiple="true"></select>
                </td>
            </tr>
        </tbody>
    </table>
</div>

<button data-bind="click: showSelectedCountries">Show Selected Countries (console log)</button>

function CountryLine(lineNumber, initialCountry) {
    var self = this;
    self.lineNumber = lineNumber;
    self.country = ko.observable(initialCountry);
}

function CountryViewModel() {
    var self = this;

    self.countryLines = ko.observableArray([]);

    // Get audit cycles
    self.availableCountries = [{
        countryId: "1",
        countryName: "Canada"
    }, {
        countryId: "2",
        countryName: "Brasil"
    }, {
        countryId: "3",
        countryName: "Australia"
    }];


    self.countryLines.push(new CountryLine("Line 1", "1"));
    self.countryLines.push(new CountryLine("Line 2", "2"));

    // Operations
    self.showSelectedCountries = function () {

        var self = this;

        for (var i = 0; i < self.countryLines().length; i++) {

            var lineNumber = self.countryLines()[i].lineNumber;
            console.log(lineNumber);
            // var selectedCountries = self.countryLine()[i].country; Question: how to extract selected countries for each row?

        }
    } // end showSelectedCountries


} // end self.scheduleAudits

ko.applyBindings(new CountryViewModel());

您可以使用selectedOptions绑定在淘汰赛中执行此操作。 查看此JSFiddle以获取信息:

http://jsfiddle.net/o6qpqkmd/2/

更新您的CountryLine对象以包括必要的数组:

function CountryLine(lineNumber, initialCountry) {
    var self = this;
    self.lineNumber = lineNumber;
    self.selectedCountries = ko.observableArray([initialCountry]);
}

并将其添加到视图中的绑定中:

<td>
    <select data-bind="options: $root.availableCountries, optionsValue: 'countryId', optionsText: 'countryName', selectedOptions: selectedCountries" multiple="true"></select>
</td>

本质上,selectedOptions绑定允许将所选值存储在模型的Observable Array中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM