Search code examples
javascriptjquerymysqltwitter-bootstrapbootstrap-accordion

Unable to keep first accordion open by default in foreach loop


I have collapsible accordion here, it is working fine with static data. Now I have linked this to database and i am trying to fetch data from database. Following is the code that i have done till now in codeingiter,

View:

<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
    <?php if($student): ?>
        <?php foreach($student as $per_student): ?> 
            <div class="panel panel-default">
                <div class="panel-heading" role="tab" id="headingTwo">
                    <h4 class="panel-title">
                        <a class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" href="#<?php echo $per_student->id; ?>" aria-expanded="false" aria-controls="collapseTwo">
                            <?php echo $per_student->name; ?>
                        </a>
                    </h4>
                </div>
                <div id="<?php echo $per_student->id; ?>" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingTwo">
                    <div class="panel-body"> 
                        <?php echo $per_student->description; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>     
    <?php endif; ?>
</div>

It is fetching the data properly, however all the accordion are closed by default but i wish that the first accordion should remain open by default and rest of them should remain closed. After that the user can open and close any accordin according to his/her own wish Can anyone please tell how i can do so


Solution

  • if you have an index count for the foreach then you could have use that to set the in class for the first iteration. The following uses $key => $per_student which will set $key as the index number.

     <?php foreach($student as $key => $per_student): ?> 
    

    Then its a case of checking if $key == 0 and if so - add the in clas which causes hte panel to be open.

        <div id="<?php echo $per_student->id; ?>" class="panel-collapse collapse 
          <?php if($key === 0){echo "in";} ?>" role="tabpanel" aria-labelledby="headingTwo">
               <div class="panel-body"> 
                 <?php echo $per_student->description; ?>
               </div> 
            </div>