Frage

I am trying to make a DIV hide/show depending on whether a Checkbox is selected or not.

Multiple items are displayed in my site, each under a DIV called .itemBox. Some colors are shown in Checkbox and I would like to hide all items besides those of the color the user picks (depending on the chosen Checkbox).

My javascript should check the ID of each .itemBox items (which is a color) and then hide/show.

So far I have my form and javascript, but nothing happens when I check a Checkbox.

FORM:

div class="colors">
<?php
$colors = mysql_query("SELECT DISTINCT color_base1 FROM item_descr ORDER BY color_base1");
while ($colorBoxes = mysql_fetch_array($colors))
{
echo "<input type='checkbox' class='regularCheckbox' name='color' value='".$colorBoxes[color_base1]."' /><font class='similarItemsText'>   ".$colorBoxes[color_base1]."</font><br />";
}
?>
</div>

JAVASCRIPT:

<script>
    $('.colors').delegate('input:checkbox', 'change', function() { 
         if ($(this).attr('checked')) {
            $(".itemBox not(#" + $(this).val()  + ")").hide();
            $(".itemBox #" + $(this).val()).show();
        }
    })
</script>

OUTPUT:

<td><div name='item' id='".$info[color_base1]."' class='itemBox'> .....
War es hilfreich?

Lösung

Here is how I would do it:

$(":checkbox").bind("click", function (event) {
     if($(this).is(':checked')) {
          $(".itemBox:not(#" + $(this).val()  + ")").hide();
          $(".itemBox[id='" + $(this).val() + "']").show();
     }else {
           //maybe you should do smth if checkbox is unchecked
     }
});

I think your mistake was the space before :not and the second selector should be like $(".itemBox[name='value']") without space before [.

Andere Tipps

Assuming based on your code that $info[color_base1] and $colorBoxes[color_base1] are the same, something like this maybe, it's hard to tell as I don't really read PHP output and database values that well ?

$('input[type="checkbox"]').on('change', function() { 
    if (this.checked) {
        $(".itemBox").hide();
        $("#" + this.value).show();
    }
});

Couple of things, you're using the color as a class in the jQuery selection but in your html its defined as the name:

<input type='checkbox' class='regularCheckbox' name='color' value='".$colorBoxes[color_base1]."' /><font class='similarItemsText'>   ".$colorBoxes[color_base1]."</font>

if you want to use the checkboxes name you could use a selector like this:

$('input[name=color]')....

remember the . notation describes a class.

take a look at this jsFiddle: http://jsfiddle.net/ufomammut66/h6m4H/

Its pretty simple but you can see the toggles show hide the next itemBox div. Your html most likely differs so that wont work for you, but since you didn't post it all I wasn't able to use correct html paths.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top