Garrett Garrett - 1 month ago 4
jQuery Question

JS How to push to array and then empty with 2 clicks

I've created this little example on JSFiddle (http://jsfiddle.net/4UvUv/198/) which allows you to click 3 button and when you click a button, it pushes a value to an array called 'selected'. So lets say I click the 'Cats' button, it will push the value 'cats' to the selected array.

But what I don't know is how to remove 'Cats' from the array if the 'Cats' button was clicked again. Would someone know how to do this using my example? Or if theres a better way?

How I push to the Selected array:

var selected = []

$("#cats").click(function(e) {
console.log("Cats");
var value = 'cats';
selected.push(value);
})

Answer

You can try something like this:

    $("#cats").click(function(e) {
      console.log("Cats");
      var value = 'cats';
      var index = selected.indexOf(value);
      if(index === -1) {
        selected.push(value);
      } else {
        selected.splice(index, 1);
      }
    });

also, it can be optimized I think

Comments