lundi 6 juillet 2015

jQuery Show Hide divs Using Checkboxes with a slight twist

There seems to be quite few examples of divs being hidden and shown via checkboxes but I have struggled to find one which tackles it in quite the same way as I am trying to do it.

What I am striving to do is create a 'simple' way of showing specific divs based on if a set of classes have been applied to different divs and then for those same divs to be hidden or shown depending on whether certain checkboxes are triggered

this is the snippet of the code:

$(document).ready(function () {

$("input[type=checkbox]").change(function () {
    var divId = $(this).attr("id");
    if ($("#expensive").is(":checked") && $(this).is(":checked") || $("#cheap").is(":checked") && $(this).is(":checked")) {
        $("." + divId).show();
    } else {
        $("." + divId).hide();
    };

In the example I added to in JSFiddle i have split the check boxes into two main categories which are colour (which is made up of: red, green, blue and purple) and prices (which is made up of: "expensive and cheap) The idea is I may wish to view all items with the class of "red" and both cheap or expensive. Alternatively I may wish to view some or all the colours but only the ones which are cheap

I have tried to cut down the code to fairly small amount but there is one sequence which seems to be tripping the logic up and for the life of me I cant think how to get it to work in this one scenario or what I may have missed.

The example is located here for people to test: http://ift.tt/1dIqrEV

works except unless you do this:

if repeat this sequence:
1. turn off either cheap or expensive
2. turn off one of the colours
3. now turn on that same colour

The result is the colour you clicked back on again shows both cheap and expensive even though one of those checkboxes is off

Every other combination seems to work and I was hoping what was written would be the most simple method but obviously something is missing and I cant see why its not giving me the results I wanted. So if anyone has any thoughts on what I have missed out then I sure would appreciate the help.

thanks in advance max




Aucun commentaire:

Enregistrer un commentaire