tags:

views:

38

answers:

2

I have a webpage having four Checkbox for example:

<p>Buy Samsung 2230<label>
<input type="checkbox" name="checkbox1" id="checkbox1" />
</label></p>
<div id="checkbox1_compare" style="display: none;"><a href="#">Compair</a></div>
<p>Buy Nokia N 95<label>
<input type="checkbox" name="checkbox2" id="checkbox2" /></label></p>
<div id="checkbox2_compare" style="display: none;"><a href="#">Compair</a></div>
p>Buy Motorola M 100<label>
<input type="checkbox" name="checkbox3" id="checkbox3" /></label></p>
<div id="checkbox3_compare" style="display: none;"><a href="#">Compair</a></div>
 <div id="checkbox2_compare" style="display: none;"><a href="#">Compair</a></div>
p>Buy LG 2000<label>
<input type="checkbox" name="checkbox4" id="checkbox4" /></label></p>
<div id="checkbox4_compare" style="display: none;"><a href="#">Compair</a></div>

I want if I will check two or more Checkbox then after every last checked check box I need a div which initially should be in hidden state to be displayed as a link that is Compare.

So below is my code:

But It should be display under the Last checked checkbox, if only two or more check box checked. and that is the compare link.

You can also get a clear understanding if you check my code:

$(document).ready(function() {
   $('input[type=checkbox]').change(function() { 
     if ($('input:checked').size() > 1) {                   
       $('#checkbox1_compare').show();              
     } 
     else { 
       $('#checkbox1_compare').hide();    
     }          
   })
});
A: 

You should try a more general model, for instance have the checkboxes contain a certain class, then use jQuery.each() to loop through them, calculate the values, and render their children divs accordingly inside the loop: jQuery(this).children('.hidden-div').show()

More info: jQuery.each(), .children()

kovshenin
+1  A: 

This might be what you want:

$(function() {
  $('input:checkbox').change(function() {
    var $ck = $('input:checkbox:checked');
    $('input:checkbox').each(function() {
      $('#' + this.id + '_compare').hide();
    });
    if ($ck.length > 1) {
      $ck.each(function() {
        $('#' + this.id + '_compare').show();
      });
    }
  });
});

That always starts by hiding all the "compare" <div> elements, then shows the ones corresponding to the checked checkboxes when 2 or more are checked.

Pointy
Missing a closing bracket after $('input:checkbox:checked' :-)
Alex
oh sorry - thanks
Pointy
Genius!!! Thanks a Lot. Please let me know where I can learn these types of concept of JQuery.