Knockout Foreach Generate Html Fields
I want to display as many fields as user wants. Maybe you have idea how can I do this case using foreach loop in Knockout framework. For example numberOfFields is input field where
Solution 1:
If I got your question right, this should be it by approx. I've also added and observable to the Quantity to show you how you could expand on the example with bound properties.
console.clear();
functionQuantity(id, label) {
var self = this;
self.id = id;
self.label = ko.observable(label);
};
ko.applyBindings(() => {
var self = this;
self.amount = ko.observable(0);
self.quantity = ko.observableArray([]);
self.amount.subscribe(function(amount) {
var quantity = self.quantity().length;
amount = Number(amount);
if (amount > quantity) {
for (var i = quantity; i < amount; i++) {
self.quantity.push(newQuantity(i+1, 'label for ' + (i+1)));
}
} elseif (amount < quantity) {
var minus = quantity - amount;
for (var i = 0; i < minus; i++) {
self.quantity.pop();
}
}
});
self.amount(2);
});
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script><label>amount: </label><inputtype="number"data-bind="textInput: amount"min="0" /><divdata-bind="foreach: quantity"><inputtype="text"data-bind="textInput: label, attr: { placeholder: 'label for ' + id }" /><spandata-bind="text: label"></span><br /></div>
Post a Comment for "Knockout Foreach Generate Html Fields"