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>