简体   繁体   中英

Toggle Divs Based on Click

Basically, I need a Points of Interest Key, that would have 8 div buttons, and when each one is clicked, would display info. Clicking them would toggle them on or off, and more than one can be shown at the same time. The eighth button when clicked, would show all. I have a rough idea of code, but I want to use jquery to detect when 8 unique DIVS are click/unclicked, i found this example using input types......

<script type="text/javascript">

$(document).ready(function(){
    $('input[type="checkbox"]').click(function(){
        if($(this).attr("value")=="red"){
            $(".red").toggle();
        }
        if($(this).attr("value")=="green"){
            $(".green").toggle();
        }
        if($(this).attr("value")=="blue"){
            $(".blue").toggle();
        }
    });
});
</script>

http://www.tutorialrepublic.com/codelab.php?topic=faq&file=jquery-show-hide-div-using-checkboxes

not an answer as such, but an observation: - you do not need all those If's... just get the value on the click of the checkbox and use that to directly target the div's toggle(). As follows:

$(document).ready(function(){
    $('input[type="checkbox"]').click(function(){
        var clicked=$(this).val();
            $("." + clicked).toggle();
    });
});

Is this what you want?

For the toggle all button, i check if all information are displayed, close all of them if true, show all of them otherwise

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>jQuery Show Hide Using Checkboxes</title> <style type="text/css"> .box{ padding: 20px; display: none; margin-top: 20px; border: 1px solid #000; } .btn, .specialBtn{ width: 35%; padding: 20px; border: 1px solid #000; cursor: pointer; } </style> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('.btn').click(function(){ var id = $(this).data("toggleid"); if(id == "0"){ // toggle all var visibleCount = $(".box:visible").length; if(visibleCount < 3) $(".box").show(); else $(".box").hide(); } else{ $("#info" + id).toggle(); } }); }); </script> </head> <body> <div> <div class="btn" data-toggleid="1">toggle info 1</div> <div class="btn" data-toggleid="2">toggle info 2</div> <div class="btn" data-toggleid="3">toggle info 3</div> <div class="btn" data-toggleid="0">toggle all</div> </div> <div class="box" id="info1">info1</div> <div class="box" id="info2">info2</div> <div class="box" id="info3">info3</div> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM