tags:

views:

35

answers:

2

I have four check boxes and when I click more than two of them then under the last clicked checkbox one I should get a <div><a href="#">Compare</a> </div> contains a compare link. It may be randomly. I tried to do this using JQuery and below is my code.I need improve one. The issue is I need when two of check box will check under the last one I should get visible the hidden div.

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

You can check the .length and use .toggle() to show/hide based on how many are checked, like this should work:

$(function() {
  $('input[type=checkbox]').change(function(){
    $('#checkbox1_compare').toggle($('input[name=checkbox1]').length > 1);
  });
}) 

If you need to move the div/link elements to be after the last checked one, something like this would work:

$(function() {
  $('input[type=checkbox]').change(function(){
    var checked = $('input[name=checkbox1]:checked');
    $('#checkbox1_compare').toggle(checked.length > 1)
                           .insertAfter(checked.last());
  });
}) 
Nick Craver
No there are four checkboxes and four Divs under that. We cannot move the one single divs. So Either or shoud display.
@user - I'm not understanding from your comment, can you post the full markup?
Nick Craver
Nick I am not getting any error while ecexuting your JQuery.
1st there are four check box its a mobile compare page where user need to check at list two check box to highlight the Compare link.
But the compare link should visible under the last checked check-box, your approach is also good where we can append the dive under every last checked check box dynamically. But above code is not working. But what if for rest check boxex?
A: 

try this: (taken based on the source of @Nick Craver)

html:

<div id="link-compare"><a href="#">Compare</a></div>

js:

$(document).ready(function() {

  var refInputCheckbox = $('input[type="checkbox"]');

  $(refInputCheckbox).change(function(){ 

    $('#link-compare')
       .toggle(
          $(refInputCheckbox).filter(':checked').length > 1
       );

  });


});
andres descalzo