saleem ahmed
saleem ahmed

Reputation: 337

show a div when atleast two checkboxes has checked

I need to show a div when two or more check boxes are checked. I Have a working JSfiddle. The JavaScript goes

 <script type="text/javascript">
                $(function(){
                 $('#checkobox').change(function(){
                   alert($('input:checked').size())
                       if($('input:checked').size() > 1){
                        $('div').show();   
                   }
                   else {
                        $('div').hide()   
                   }
                 });
            </script>

The html content

         <input type="checkbox" id="one"></input>
         <input type="checkbox" id="one"></input>
         <input type="checkbox" id="one"></input>
         <div style="display: none;">At least 2 are checked</div>

I have another script in same page to select all, is it conflict this two checkbox selecting.

<script language="javascript" type="text/javascript">
                $(document).ready(function() {
                $('#checkall').click(function(event) {  //on click 
                    if(this.checked) { // check select status
                        $('.checkbox1').each(function() { 
                            this.checked = true;                
                        });
                    }else{
                        $('.checkbox1').each(function() { 
                            this.checked = false;                    
                        });         
                    }
                });
            });
       </script>

This code works fine, but not in local host and server. Show your skills...and give me a solution..thanks

Upvotes: 1

Views: 2377

Answers (1)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28523

You need to wrap your script inside $(function(){ or $(document).ready(function(){ so that it will bind change event to checkboxes when whole DOM is ready. Also make sure that you have included jQuery library in your HTML but before your script.

EDIT : - to remove conflict with another script, you can put class="one" for your checkboxes (I have removed id="one" as you cannot use same id for multiple elements) as shown below and change the script accordingly

HTML

<input type="checkbox" class="one"></input>
<input type="checkbox" class="one"></input>
<input type="checkbox" class="one"></input>
<div style="display: none;">At least 2 are checked</div>

jQuery :

$(function(){
  $('input[type=checkbox].one').change(function(){
    alert($('input[type=checkbox].one:checked').size())
        if($('input[type=checkbox].one:checked').size() > 1){
         $("div").show();   
    }
    else {
         $('div').hide()   
    }
  });
});

JSFiddle Demo

Upvotes: 3

Related Questions