Knockout Js: Get Dropdown Selected Data And Populate Other Fields
Using Knockout JS here. I have a HTML table and the table has 4 columns. I have button to add a row to table and then remove button against each row to delete it. I also have a dro
Solution 1:
You've got some parent and level stuff mixed up, and your table was binding on value
instead of text
. I moved the drop down binding, selectedValue
to Item
since it's at the row level and not the parent level. I used the KO with
binding to show the values inside selectedValue
for that part of the HTML.
I also added a <pre>
tag with the KO values so you can see what happens as you interact with it and the KO model data changes.
Side note: The three properties in Item
don't need to be observable in this demo as the values do not change while on the screen.
varViewModel = function() {
var self = this;
//Empty Row
self.items = ko.observableArray([newItem()]);
self.ddl = ko.observableArray();
self.addRow = function() {
self.items.push(newItem());
};
self.removeRow = function(data) {
self.items.remove(data);
};
self.GetData = function() {
if (self.ddl().length === 0) {
var item1 = newItem("Alex", "Sanders", "Maple Street");
self.ddl.push(item1);
var item2 = newItem("Sam", "Billings", "Mahony Street");
self.ddl.push(item2);
}
}
}
varItem = function(fname, lname, address) {
var self = this;
self.firstName = ko.observable(fname);
self.lastName = ko.observable(lname);
self.address = ko.observable(address);
self.selectedValue = ko.observable();
};
vm = newViewModel()
vm.GetData();
ko.applyBindings(vm);
<linkhref="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css"rel="stylesheet" /><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script><tableclass="table table-bordered"><theadclass="mbhead"><trclass="mbrow"><th>Input</th><th>First Name</th><th>Last Name</th><th>Address</th></tr></thead><tbodydata-bind="foreach: items"><tr><td><selectclass="form-control"data-bind="options: $parent.ddl, optionsText: 'firstName', value: selectedValue, optionsCaption: '--Select--'"></select></td><tddata-bind="with: selectedValue"><spandata-bind="text: firstName"></span></td><tddata-bind="with: selectedValue"><spandata-bind="text: lastName"></span></td><tddata-bind="with: selectedValue"><spandata-bind="text: address"></span></td><td><inputtype="button"value="Remove Row"data-bind="click: $parent.removeRow"class="btn btn-danger" /></td></tr></tbody></table><divclass="col-xs-12 col-sm-6"><inputtype="button"value="Add Row"class="btn btn-primary"data-bind="click: addRow" /></div><predata-bind="text: ko.toJSON($data, null, 2)"></pre>
Post a Comment for "Knockout Js: Get Dropdown Selected Data And Populate Other Fields"