开发者

Show div based on selected checkboxes

开发者 https://www.devze.com 2023-01-21 03:57 出处:网络
I have a webpage having four Checkboxes as follows: <p>Buy Samsung 2230<label> <input type=\"checkbox\" name=\"checkbox1\" id=\"checkbox1\" />

I have a webpage having four Checkboxes as follows:

<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" sty开发者_如何学JAVAle="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>

If I 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.

Below is my code:

However, It should be displayed under the last checked checkbox, if only two or more checkboxarees 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();    
     }          
   })
});


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.


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()

0

精彩评论

暂无评论...
验证码 换一张
取 消