First, the event you are using to check if a checkbox was selected is not the correct one ( click
). For this action, it is best to use change
:
$("input[name='estrelas']").on('change', function(){ ...});
To solve the problem of removing the add a hotel to the final list, I added a variable that says whether or not the item was selected in the filtro
function:
function filtro(valor, selecionado) {...}
This value comes from the checked
property of the element that is receiving the change
event mentioned above. In this case we can reference this element with this
:
filtro(value, this.checked);
To maintain the status of selected elements among selection events, I have created a global variable called hotels
, which will contain the selected hotels:
var hotels = [];
This variable will be populated within the filtro
fault function, depending on the value selecionado
:
if (selecionado) {
Array.prototype.push.apply(hotels, json.hotelPesquisa.filter(function(hotel) {
return hotel.hotel.qtEstrela == valor;
}));
} else {
hotels = hotels.filter(function(hotel) {
return hotel.hotel.qtEstrela != valor;
});
}
If the value passed to the filtro
function was selected, we used the apply
to merge an array with another array. Another alternative to this step is to use the concat
:
hotels = hotels.concat(json.hotelPesquisa.filter(function(hotel) {
return hotel.hotel.qtEstrela == valor;
}));
If the user has removed the value selection, that is the value this.checked == false
, then we only filter the array hotels
and we get the values other than the value that the user removed:
hotels = hotels.filter(function(hotel) {
return hotel.hotel.qtEstrela != valor;
});
Follow JSFiddle with the solution: link