0

I'm trying to create a multi-filter and I am having difficulty with the JS code. It is necessary add category attr into the array when clicking, and deleted from it when it is clicked again.

Here is my code that is not working correctly.

$('span[data-genre]').click(function(event) {

  var genre = [];
  var category = $(this).attr('data-genre');

  if ($(this).hasClass("active")) {
    $(this).removeClass('active');
    var removeItem = $(this).attr('data-genre');
    genre = $.grep(genre, function(value) {
      return value != removeItem;
    });

    alert(genre);
  } else {
    $(this).addClass('active');
    genre.push($(this).attr('data-genre'));
    alert(genre);
  }
});
span {
  display: block;
  font-size: 22px;
  font-weight: bold;
  margin: 10px;
  cursor: pointer;
}

span:hover {
  color: green;
}

.active {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-genre="1">1</span>
<span data-genre="2">2</span>
<span data-genre="3">3</span>
<span data-genre="4">4</span>

1 Answer 1

1

You just need to move var genre = []; outside the click event.

Since it's inside your click event, then it will reset every time you click on an object

Demo

var genre = [];
$('span[data-genre]').click(function(event) {

  var category = $(this).attr('data-genre');

  if ($(this).hasClass("active")) {
    $(this).removeClass('active');
    var removeItem = $(this).attr('data-genre');
    genre = $.grep(genre, function(value) {
      return value != removeItem;
    });

    console.log(genre);
  } else {
    $(this).addClass('active');
    genre.push($(this).attr('data-genre'));
    console.log(genre);
  }
});
span {
  display: block;
  font-size: 22px;
  font-weight: bold;
  margin: 10px;
  cursor: pointer;
}

span:hover {
  color: green;
}

.active {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span data-genre="1">1</span>
<span data-genre="2">2</span>
<span data-genre="3">3</span>
<span data-genre="4">4</span>

Sign up to request clarification or add additional context in comments.

1 Comment

Good eye, beat me to it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.