Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

array.splice is not a function

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.

like image 331
Juan Rangel Avatar asked Oct 16 '25 17:10

Juan Rangel


1 Answers

cats 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);
}
like image 99
Walter Chapilliquen - wZVanG Avatar answered Oct 18 '25 05:10

Walter Chapilliquen - wZVanG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!