Knockout foreach generate html fields

我怕爱的太早我们不能终老 提交于 2021-01-29 08:55:03

问题


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 user can enter how many fields he wants to display

<input id="numberOfFields" type="text" data-bind="value: obj().numberOfFields() />
<div data-bind="foreach: new Array(obj().numberofCashFlows())">
   <label for="quantity$index()">Flow number $index()</label>
   <input id="quantity$index()" type="text" data-bind="value: quantityArray[$index()]" />
</div>

Of course code doesn't work, I want to tell you what I mean.

If user enters 3 I want to show 3 labels and inputs with id quantity1, quantity2, quantity3 and with values: quantityArray[0], quantityArray[1], quantityArray[2]

Can you help me or give some advice?


回答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();

function Quantity(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(new Quantity(i+1, 'label for ' + (i+1)));
      }
    } else if (amount < quantity) {    	
    	var minus = quantity - amount;
      for (var i = 0; i < minus; i++) {
      	self.quantity.pop();
      }
    }
  });
  
  self.amount(2);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label>amount: </label>
<input type="number" data-bind="textInput: amount" min="0" />
<div data-bind="foreach: quantity">
    <input type="text" data-bind="textInput: label, attr: { placeholder: 'label for ' + id }" /><span data-bind="text: label"></span><br />
</div>


来源:https://stackoverflow.com/questions/59427173/knockout-foreach-generate-html-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!