I have four inputs like this:
<input type="text" data-bind="value: Id" />
<input type="text" data-bind="value: Id" />
<input type="text" data-bind="value: Id" />
<input type="text" data-bind="value: Id" />
I need to retrieve data from this inputs and put them into array. I've tried to do it like this:
`var data = [];
var viewModel = {
Id: ko.observable(),
Ids: ko.observableArray(data),
showReports: function () {
var container = $('input[type=text]');
container.each(function() {
if (container.val().trim().length > 0) {
data.push({ Id: container.val() });
}
});
}
};
ko.applyBindings(viewModel);`
When I fill in first input with data, the others are filled as well,but I need to put there other data. How can I cope with this? In the future I will have more than 4 inputs.
Try this (untested):
<!-- ko foreach: Ids -->
<input type="text" data-bind="value: Id" />
<!-- /ko -->
var data = [];
var viewModel = function () {
var self = this;
this.Id = ko.observable();
this.Ids = ko.observableArray([{ Id: 1 }, { Id: 2 }, { Id: 3 }]);
this.showReports = function () {
for(var i = 0; i < self.Ids().length)
data.push(self.Ids()[i];
}
};
ko.applyBindings(new viewModel());