mercredi 25 octobre 2017

Multiple checkbox remove non shared values in javascript

So I have the following problem.

I have a set of checkboxes. First one describes categories (say some kind of businesses), and they have associated with them certain facilities.

Let's say I have

Restaurant: Parking, Free WIFI
Hotel: Venues, Parking, Free WIFI, Lunch, Drinks
Bar: Parking, Drinks

I have this information in a object I can access called typeFacilitiesLinks

{Restaurant: ["Parking", "Free WIFI"],
Hotel: ["Venues", "Parking", "Free WIFI", "Lunch", "Drinks"],
Bar: ["Parking", "Drinks"]}

So when I check Restaurant checkbox, the Parking and Free WIFI checkboxes show. When I click Bar Drinks will be shown.

var checkedArrayFacilities = [];

$(document).on('click', '.industry-checkbox', toggleFacilitiesShow);

function toggleFacilitiesShow(e) {
    var $this = $(e.currentTarget);
    var checkedIndustry = $this.val(); // E.g. Restaurant
    var $facilitiesContainer = $('.facilities_container');

    if ($this.is(':checked')) {
        var index = checkedArrayFacilities.indexOf(checkedIndustry);

        if (index > -1) {
            checkedArrayFacilities.splice(index, 1);
        } else {
            checkedArrayFacilities.push(checkedIndustry);
        }

        for (var el in typeFacilitiesLinks) {
            if (typeFacilitiesLinks.hasOwnProperty(el)) {
                if (el === checkedIndustry) {
                    $facilitiesContainer.find('.check-facility').each(function(){
                        var $input = $(this);
                        if ( $.inArray( $input.val(), typeFacilitiesLinks[checkedIndustry] ) !== -1 ) {
                            $input.parents('.single_check').addClass('show');
                           $facilitiesContainer.removeClass('hidden');
                        }
                    });
                }
            }
        }
    }
}

This works fine. What I cannot figure out is how to remove the facilities, but only those that are not repeating in the other facilities. Imagine I have all three businesses checked. I have all their facilities shown. Now if I remove Restaurant, nothing should change, since Hotel has Free WIFI, and Parking, and Bar has also Parking.

But If I had Restaurant and Bar checked and removed Bar, I should only loose the Drinks checkbox, not the Parking one.

The more options I have checked, and more facilities shown, the more this relationship becomes :S

What is the best way to fix this? All I got was just removing the facilities from the checked option, and that's no good.




Aucun commentaire:

Enregistrer un commentaire