MANnDAaR
MANnDAaR

Reputation: 2590

Make div appears if any of the checkbox is checked!

I am working on dynamic site where multiple checkboxes are there with unique ID,

What I want is new <div> to appear if any of the checkbox is checked & disappears if all the checkboxes are unchecked.

New to javascripts, need your help.

Thanks

Upvotes: 3

Views: 2154

Answers (3)

kamui
kamui

Reputation: 3419

I recently had to do something similar using jQuery.

First hide the area onload so the user cannot see it

 <style>
     #div2appear{
         display: none;
     }
 </style>

Then the form elements

 <form id="AllTheseFields">
   <input type="checkbox" name="c1" />
   <input type="checkbox" name="c1" />
   <input type="checkbox" name="c1" />
   <input type="checkbox" name="c1" />
   <input type="checkbox" name="c1" />
   <div id="div2appear">
     <input type="text" />
   </div>
 </form>

And the jQuery

 <script type="text/javascript">
    $('#AllTheseFields>input[type=checkbox]').change(
       function(){
           if($('#AllTheseFields>input[type=checkbox]').is(':checked')){
                  // if any of the checkboxes are checked then make the area visible
                  $('#div2appear').show(); 
           }else{
                  // only if all are unchecked will this fire and hide the area
                  $('#div2appear').hide();
           }
       }
    );
 </script>

Upvotes: 1

MANnDAaR
MANnDAaR

Reputation: 2590

<style>
 #appear_div {
     display: none;
 }
</style>

<script type="text/javascript">
 function doInputs(obj){
 var checkboxs = $("input[type=checkbox]:checked"); 
 var i =0, box;
 $('#appear_div').fadeOut('fast');
     while(box = checkboxs[i++]){
     if(!box.checked)continue;
     $('#appear_div').fadeIn('fast');
     break;
     }
 }
 </script>

 <form>
 <input type="checkbox" name="c1" onclick="doInputs(this)">
 <input type="checkbox" name="c1" onclick="doInputs(this)">
 <input type="checkbox" name="c1" onclick="doInputs(this)">
 <input type="checkbox" name="c1" onclick="doInputs(this)">
 <input type="checkbox" name="c1" onclick="doInputs(this)">
 </form>
 <div id="appear_div">
 <input type="text">
 </div>

This worked for me.

Thanks

Upvotes: 1

Haim Evgi
Haim Evgi

Reputation: 125526

recommended to learn Jquery

http://jquery.org/

you can put an ascending id like chekboxid1 , checkboxid2 ....

and check if all be checked :

$('[id^=checkboxid]').live('click', function(){
var total = {insert the sum of checkbox}
    if($("[id^=checkboxid]:checked").length == total){
    // do something
}
});

to know if all unchecked compare the length 0 , instead of total.

another link more detailed :

http://charlie.griefer.com/blog/index.cfm/2009/8/14/jQuery--Accessing-Checked-Checkboxes

Upvotes: 1

Related Questions