Array.splice is not a function
I am trying to remove an element from an array not marked with this bit of code.
function filterSearch() {
var cats = [];
$('.filter-by-type input[type="checkbox"]').change(function() {
var cat = $(this).attr('name') + ', ';
if(this.checked) {
cats += cat;
} else {
cats.splice(cats.indexOf(cat), 1);
}
console.log(cats);
});
}
filterSearch();
I am getting the error Uncaught TypeError: cats.splice is not a function
Basically, I want to add a value to the array cats[]
if the item is checked and removed if not set. Any help would be greatly appreciated.
+3
source to share
1 answer
cats
- array. Here:
if(this.checked) {
cats += cat;
^^
} else {
cats.splice(cats.indexOf(cat), 1);
}
You are trying to concatenate an array with an operator +=
is cats
now a string, you should use push instead.
if(this.checked) {
cats.push(cat);
} else {
cats.splice(cats.indexOf(cat), 1);
}
+8
source to share