Amit Kushwaha
Amit Kushwaha

Reputation: 101

How to do hide and show my div through checkbox

In following code I don't know how many rows is here which is dynamic. first of all we have to all div hidden. When i checked(//first input) after checked checkbox only it's div should be visible.

<?php 
    $checkboxid=0;
    foreach($products as $product){ 
        $checkboxid = $checkboxid+1;
?>
    <tr>
       <td class="text-center">
          //first input<input name="checkbox[]" type="checkbox" value="<?php echo $product['id'];?>" id="<?php echo $checkboxid; ?>"><br/>              
          <div class="<?php echo $checkboxid; ?>">
              <input name="chile" type="checkbox" value="" ><br/>
              <input name="miami" type="checkbox" value="" >
          </div>
       </td>
    </tr>
<?php } ?>

Upvotes: 2

Views: 233

Answers (2)

Norlihazmey Ghazali
Norlihazmey Ghazali

Reputation: 9060

Use class for easy implementation like so :

<input name="checkbox[]" type="checkbox" value="<?php echo $product['id'];?>" id="<?php echo $checkboxid; ?>" class="myCheckBox">

Then attach change handler onto myCheckBox class like below :

$(document).on('change', '.myCheckBox', function () {
  // or .next().next() change to .nextAll('div')
  // in case only one of div element are existed
  if ( this.checked ) $(this).next().next().show();
  else  $(this).next().next().hide();
});

For better approach put class inside respective div like so :

<div class="<?php echo $checkboxid; ?> myDiv">
    <input name="chile" type="checkbox" value="" ><br/>
    <input name="miami" type="checkbox" value="" >
</div>

Then in js code just filtered next input with matched selector only :

$(document).on('change', '.myCheckBox', function () {      
  if ( this.checked ) $(this).nextAll('.myDiv').show();
  else  $(this).nextAll('.myDiv').hide();
});

Updated

I don't know there How many rows so we can not use any static id or class

In this case, class is suitable for you

DEMO

Upvotes: 2

Arijit Mukherjee
Arijit Mukherjee

Reputation: 3875

$(document).ready(function () {
$('#checkbox1').change(function () {
    if (!this.checked) 
       $('#autoUpdate').fadeIn('slow');
    else 
        $('#autoUpdate').fadeOut('slow');
});
});

you can do like this

DEMO

Upvotes: 0

Related Questions