Skip to content Skip to sidebar Skip to footer

Remove Items From Knockout Observable Array

I have the below structure for knockout model. It contains an observable array which in turn contains an object. function ViewModel() { var self = this; self.newItem =

Solution 1:

Try the following for adding new item, which will solve your first issue:-

HTML code

<inputtype="text"id="textBox"data-bind="value : textBoxVal"/><div>
    Items: <buttondata-bind="click: addItem">Add Item</button></div><div><table><tbodydata-bind="template: { name: 'itemTemplate', foreach: AllItems }"></tbody></table></div><scripttype="text/html"id="itemTemplate"><tr><td><inputdata-bind="value: itemnumber" /><ahref="#"data-bind="click: $parent.removeItem">Remove Item</a></td></tr></script>

JS code:-

functionViewModel() {
varself = this;

self.newItem = ko.observable({        
    manufacturer: "",
    itemnumber: "",
    itemDescription: ""   

});

 self.textBoxVal = ko.observable();
 self.AllItems = ko.observableArray();      

self.addItem = function() { 
 self.newItem().manufacturer= "test"; 
 self.newItem().itemDescription= "data";
 self.newItem().itemnumber = self.textBoxVal();

self.AllItems.push(self.newItem); 

};
self.removeItem = function(data) { 
    self.AllItems.remove(data);
};
}
$(document).ready(function() {ko.applyBindings(new ViewModel()); });

Your first issue was because, each time you are trying to add a new item, you were changing the value of itemNumber, which is an observable.

Observable value will be changed every where it is binded, when it's value is changed.

Instead you need to create new object and do push into the observableArray.

Refer doc to know more about observableArray.

For your second problem change removeItem as given below:-

self.removeItem = function(data) {
var dtIndex = self.AllItems.indexOf(data); //Get the index of the object you want to remove.self.AllItems.splice(dtIndex, 1); //Then do splice
};

You can refer the above doc, to know how to use splice.

EDIT based on the suggestion in the comment :-

For working code of edited answer click here.

Hope this will solve your problem.

Post a Comment for "Remove Items From Knockout Observable Array"