1
votes

Basically I have a list and each item in the list has a unique value. If a list item is clicked on, I want the value to be added or removed from an observable array. So if that value exists in the array, I want to remove it and vice-versa.

The structure of the array would be simple:

var items = ko.observableArray([
    "value1",
    "value2"
]);

The list will have inputs with value1 and value2. If the list with value2 is clicked on, I want to remove it from the array, and if it doesn't, I need to push it to the array.

So basically I need to toggle an item in the array.

Is this possible with knockout.js? Thanks!

1

1 Answers

2
votes

Sure. Knockout's observableArray has an indexOf method built right in. Use it, along with push and remove to do what you're asking. Something like this should work:

function toggle(value){
    if (items.indexOf(value) < 0){
        //it's not in the array - push it
        items.push(value);
    } else {
        //it's there - remove it
        items.remove(value);
    }
}