Is it possible to extract selected items from a multi-select Select HTML element when these elements are embedded in table rows?
Please check jsFiddle
How can I list the selected country ids for each row when using Knockout.js? How do I use the selectedValues option for each row?
<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());
You can do this in Knockout using the selectedOptions binding. Check out this JSFiddle for information:
http://jsfiddle.net/o6qpqkmd/2/
Update your CountryLine object to include the necessary array:
function CountryLine(lineNumber, initialCountry) {
var self = this;
self.lineNumber = lineNumber;
self.selectedCountries = ko.observableArray([initialCountry]);
}
And add it to the binding in the view:
<td>
<select data-bind="options: $root.availableCountries, optionsValue: 'countryId', optionsText: 'countryName', selectedOptions: selectedCountries" multiple="true"></select>
</td>
Essentially the selectedOptions binding allows to to store the selected values in an Observable Array on the model.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.