First the event you are using to check if a checkbox has been selected is not the most correct (click
). For such action, it is best to use the change
:
$("input[name='estrelas']").on('change', function(){ ...});
To solve the problem of removing adding a hotel to the final list, I added a variable that says whether or not the item was selected in the function filtro
:
function filtro(valor, selecionado) {...}
This value comes from the property checked
of the element receiving the event change
mentioned above. In this case we can reference this element with the this
:
filtro(value, this.checked);
To maintain the status of selected elements among the selection events, I created a global variable called hotels
, which will contain the selected hotels:
var hotels = [];
This variable will be populated within the function filtro
, 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 function filtro
has been selected, we use the method apply
to merge an array with another array. Another alternative to this step is to use the method concat
:
hotels = hotels.concat(json.hotelPesquisa.filter(function(hotel) {
return hotel.hotel.qtEstrela == valor;
}));
If the user has removed the value selection, ie the value this.checked == false
, then we just filter the array hotels
and we get values other than the value that the user has removed:
hotels = hotels.filter(function(hotel) {
return hotel.hotel.qtEstrela != valor;
});
Follow Jsfiddle with the solution: https://jsfiddle.net/xrkuoqhq/9/
Could you help me? https://answall.com/questions/224461/problema-com-filtro-jquery
– usuario