KnockoutJS - remove() Method


Advertisements

Description

The KnockoutJS Observable remove('value') method removes the items matching with the 'value' and returns as an array.

Syntax

arrayName.remove('value')

Parameters

Accepts one parameter as a value to be removed.

Example

<!DOCTYPE html>
   <head>
      <title>KnockoutJS ObservableArray remove method</title>
      <script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
         type = "text/javascript"></script>
   </head>

   <body>
      <p>Example to demonstrate remove() method.</p>
      <button data-bind = "click: removeEmp">Remove selected Emp</button>
      <p>Array of employees:</p>
      <select multiple = "true" size = "8" data-bind = "options: empArray , 
         selectedOptions: chosenItem"> </select>

      <script>
         function EmployeeModel() {
            this.empName = ko.observable("");
            this.chosenItem = ko.observableArray("");
            this.empArray = ko.observableArray(['Scott','James','Jordan','Lee',
               'RoseMary','Kathie']);

            this.removeEmp = function(chosenItem) {
               
               if (this.chosenItem().length == 0)  {
                  alert("Please select item/s to be removed.");
               }
               
               while(this.chosenItem().length > 0) {
                  this.empArray.remove(this.chosenItem()[0]);
               }
            }
         }

         var em = new EmployeeModel();
         ko.applyBindings(em);
      </script>
      
   </body>
</html>

Output

Let's carry out the following steps to see how the above code works −

  • Save the above code in array-remove.htm file.

  • Open this HTML file in a browser.

  • Select the item to be removed from the list and click the Remove selected Emp Button.

knockoutjs_observables.htm
Advertisements