Warning message for duplicated items
HTML
<table>
<tbody data-bind="foreach:dataValues">
<tr>
<td data-bind="text: stepNo"></td>
<td data-bind="text: stepText"></td>
</tr>
</tbody>
</table>
<table>
<tbody data-bind="foreach:dataValues">
<tr>
<td>
<input type="text" data-bind="value: stepNo" />
</td>
<td>
<input type="text" data-bind="value: stepText" />
<p data-bind="visible: notUniqueHint, text: notUniqueHint">
</p>
</td>
</tr>
</tbody>
</table>
JavaScript
function Step(no, text, parentObject) {
var self = this;
var parent = parentObject;
self.stepNo = ko.observable(no);
self.stepText = ko.observable(text);
self.notUniqueHint = ko.computed(function () {
var duplicate = ko.utils.arrayFirst(parent.dataValues(), function (item) {
return item.stepText() == self.stepText() && item.stepNo() != self.stepNo();
})
if (duplicate) {
return "Item is duplicated Step #" + duplicate.stepNo() + " with text - " + duplicate.stepText();
}
return "";
});
}
function UniqueViewModel() {
var self = this;
self.dataValues = ko.observableArray();
self.dataValues.push(new Step(1, "Test1", self));
self.dataValues.push(new Step(2, "Test2", self));
self.dataValues.push(new Step(3, "Test3", self));
}
ko.applyBindings(new UniqueViewModel());