JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" data-bind="value: modelName" />
<div data-bind="foreach: addresses">
<input type="text" data-bind="value: $rawData.address, valueUpdate: 'input'" />
<button data-bind="click: $parent.removeAddress">Remove</button>
<br/>
</div>
<button data-bind="visible: allowAddMore, click: addNew">Add</button>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
JavaScript
var Model = function() {
var self = this;
self.modelName = ko.observable("modelName");
self.maxCount = 4;
self.addresses = ko.observableArray();
self.addUser = function(email) {
self.addresses.push({address: email});
};
self.removeAddress = function(email) {
self.addresses.remove(email);
}
self.hasEmpty = ko.computed(function() {
var hasBlank = false;
ko.utils.arrayForEach(self.addresses(), function(item){
if (item.address === ""){
hasBlank = true;
return;
}
});
return hasBlank;
});
self.allowAddMore = ko.computed(function() {
return self.hasEmpty() === false && self.addresses.length <= self.maxCount;
});
self.addNew = function() {
if (!self.hasEmpty()){
self.addresses.push({address: ''});
}
};
};
var vm = new Model();
vm.addUser("foo@bar.com");
vm.addUser("foo1@bar1.com");
vm.addUser("foo2@bar2.com");
vm.addUser("foo3@bar3.com");
ko.applyBindings(vm);