I am trying to remove an item from an array of unchecked 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 the value to the cats[]
array if the item is checked and removed if unchecked. Any help would be appreciated.
I am trying to remove an item from an array of unchecked 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 the value to the cats[]
array if the item is checked and removed if unchecked. Any help would be appreciated.
1 Answer
Reset to default 10cats
is a array. Here:
if(this.checked) {
cats += cat;
^^
} else {
cats.splice(cats.indexOf(cat), 1);
}
You are trying to concatenate an array with the +=
operator, cats
is now a string, you should use the push method instead.
if(this.checked) {
cats.push(cat);
} else {
cats.splice(cats.indexOf(cat), 1);
}