husin.anti husin.anti - 4 months ago 25
Javascript Question

jQuery toggle on PHP foreach loop

Using codeigniter 3.x

i'm trying to get data from database using foreach loop.

<h3 style="margin-right:15px;" id='hideshow'>August 2016</h3>
<?php foreach($duxeos as $e): ?>
<div class='content' ><h4 class="dropdate"><?php echo $e->fulldate;?></h4><div class="cdropdate" class="defhide"><?php echo $e->content;?></div></div>
<?php endforeach; ?>


javascript :

jQuery(document).ready(function(){
jQuery('.hideshow').live('click', function(event) {
jQuery('.content').toggle('show');
});
});

jQuery(document).ready(function(){
jQuery('.dropdate').live('click', function(event) {
jQuery('.cdropdate').toggle('show');
});
});


now it's working, but when i press the hide button, it hide all content, how can i hide content that i want ?

Answer
  • Use this context in handler-function
  • Use .on instead of .live
  • Use .closest to get the closest element in order to find child of it.

jQuery(document).ready(function() {
  jQuery('.dropdate').on('click', function(event) {
    jQuery(this).closest('.content').find('.cdropdate').toggle();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<h3 style="margin-right:15px;" id='hideshow'>August 2016</h3>
<div class='content'>
  <h4 class="dropdate">Full-Date</h4>
  <div class="cdropdate defhide">Content</div>
</div>
<hr>
<div class='content'>
  <h4 class="dropdate">Full-Date</h4>
  <div class="cdropdate defhide">Content</div>
</div>