Javascript to collapse Bootstrap table rows

I have some javascript that expands a table row on click, the row expands fine and if I select  a row above the row I have just expanded, that expands too. However, if I select a row below the an expanded row, it does does expand slightly but not with the content that appears in the rows above. (hope this makes sense.

What I would like to do is to close all expanded rows before it opens the one selected  so that there can only be one expanded row expanded at a time, but not sure how to do this. I assume i would have to do this wth a class. Am new to javascript, so I may be missing something obvious.

Thanks in advance

Code below;

                     // ROW EXPANDER CONSTRUCT =================================================================
                                var $table = $('#testTable');

                                $table.on('expand-row.bs.table', function(e, index, row, $detail) {
                                var res = $("#desc" + index).html();
                                $detail.html(res);                                                               
                                });

                                $table.on("click-row.bs.table", function(e, row, $tr) {
                                
                                // Get selected row
                                var tbl = document.getElementById("testTable");
                                if (tbl != null) {
                                for (var i = 0; i < tbl.rows.length; i++) {
                                    tbl.rows[i].onclick = function () { getRowVal(this); };
                                    }
                                }

                                        function getRowVal(row) {
                                        var rowVal = parseInt(row.rowIndex);
                                        var rowVal = rowVal-1
                                        console.log('Row selected - '+ rowVal)                                                            
                                   
                                if ($tr.next().is('tr.detail-view')) {

                                      $('.spanEdit').attr('class', 'spanEdit'); 
                                      $table.bootstrapTable('collapseRow', $tr.data('index')); 
                                                                        
                                } 
                                       else {                                       
                                                                              
                                        $('.spanEdit').attr('id', 'desc'+rowVal);                                                                              
                                        $table.bootstrapTable('expandRow', $tr.data('index'));

                                   }
                               
                                }

                                });

Open in new window

martmacAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Leonidas DosasCommented:
Sample code/data

Could you post the HTML-CSS  code of the table?
martmacAuthor Commented:
HTML below, please note that the table is dynamically populated from an object called data1 which is jSon Data, so what you see below is before the table is populated. The css is controlled by the bootstrap css, but there are a few lines of custom css to deal with table hover and row select. Do you need to see those. I think all I need is some javascript to collapse all expanded rows, this would solve my problem. As each of the expanded elements have the same class, if I knew how to collapse a row by using the class, that would be great.

By way of background, the expanded rows come from the span with the class spanEdit, this is created on the fly and added to the row as the expanded element.

                            </div>                                                   
                            <div class="table" >
                                <table id="testTable" 
                                class="table table-striped pagination-primary
                                table-hover 
                                table-responsive"
                                data-toggle="table"
                                data-show-export="true"
                                data-pagination="false"                                                                                               
                                data-search="true"
                                data-detail-view="true"
                                data-show-refresh="true"                                                       
                                data-click-to-select="true">                                                                                                        

                    <!-- <caption>List of users</caption> -->
                    <thead class="thead-dark">
                            <tr>
                            <th data-field="Client_ID" data-visible="false">Client_ID </th>
                            <th data-field="Salutation" data-sortable="true">Title</th>
                            <th data-field="FirstName" data-sortable="true">First Name</th>
                            <th data-field="Surname" data-sortable="true">Surname</th>
                            <th data-field="Tel" data-sortable="true">Tel</th>
                            <th data-field="Email" data-sortable="true">Email Address</th>
                            </tr>
                                </thead>
                                <tbody>
                                <tr>
                                <th scope="row">1</th>
                                <td>Mark</td>
                                <td>Otto</td>
                                <td>@mdo</td>
                                <td>other content</td>
                                <span class="spanEdit"style="display: none;" id="desc3">
                                            <div id="expanderWrap" class="ExpanderWrap"><h4>Description:</h4>
                                            <br>
                                            <div id="expanderContainer" class+"expContainer">
                                            This is row with id=0, containing other content
                                            <p>I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. So when you get something that has the name Kanye West on it, it’s supposed to be pushing the furthest possibilities. I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus.</p>
                                        </div>
                                    </div>
                                </span>
                                </tr>
                            </tbody>
                        </table>
                            </div>
                                </div>
                                    </div>
                                        <div class="tab-pane" id="messages" role="tabpanel">
                                            <p>I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. So when you get something that has the name Kanye West on it, it’s supposed to be pushing the furthest possibilities. I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus.</p>
                                        </div>
                                        <div class="tab-pane" id="settings" role="tabpanel">
                                            <p>
                                            "I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus. I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at."
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            </div>  

Open in new window

Leonidas DosasCommented:
As i debug your js code I have notice some syntactical and logical errors as they seems at the image below...\
Capture.JPGThe on() method takes the parameters as it show below
Capture1.JPGAlso at the
$table.on("click", function(e, row, $tr){
//some code here
});

Open in new window

you don't pass the $tr parameter
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

martmacAuthor Commented:
Sorry there was a slight error in the script, see below, I have annotated

                                // ROW EXPANDER CONSTRUCT =================================================================
                                var $table = $('#testTable');


                                $table.on('expand-row.bs.table', function(e, index, row, $detail) {
                                var res = $("#desc" + index).html();// the html of the span is what is being passed as a string to the expanded row.
                                $detail.html(res);                                
                                
                                });

                                $table.on("click-row.bs.table", function(e, row, $tr) {
                                
                                // Get selected row
                                var tbl = document.getElementById("testTable");
                                if (tbl != null) {
                                for (var i = 0; i < tbl.rows.length; i++) {
                                    tbl.rows[i].onclick = function () { getRowVal(this); };
                                    }
                                }
                                        // Get the clicked row value using this function
                                        function getRowVal(row) {
                                        var rowVal = parseInt(row.rowIndex);
                                        var rowVal = rowVal-1
                                        console.log('Row selected - '+ rowVal)                                                            
                                   
                                if ($tr.next().is('tr.detail-view')) {
                                   
                                   //  the row value that is obtained above is passed in the code below to provide the 'index'
                                    $('.spanEdit').attr('id', 'desc'+rowVal);  // this is the value that is passed to the index below 

                                    $table.bootstrapTable('collapseRow', $tr.data('index')); // this index is then used to collapse the required row
                                                                        
                                } 
                                       else {                                       
                                                                              
                                        $('.spanEdit').attr('id', 'desc'+rowVal); // again rowVal is passed to the index and this expands the row                                                                              
                                        $table.bootstrapTable('expandRow', $tr.data('index'));

                                   }
                               
                                }

                                });

Open in new window


What I want to do is pass a value that collapses all rows that are expanded, this is where I am struggling
Leonidas DosasCommented:
Check this script. When you are clicking in the tr element it collapsed.When you are clicking on the button the tr elements are appearing. The function working as this. When I click the tr then the function adds a classname="collapse" in the specific tr.When I click on the button then the function removes all the className="collapse" from the tr elements.
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
	<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
<body>
	 <div class="table" >
                                <table id="testTable" 
                                class="table table-striped pagination-primary
                                table-hover 
                                table-responsive"
                                data-toggle="table"
                                data-show-export="true"
                                data-pagination="false"                                                                                               
                                data-search="true"
                                data-detail-view="true"
                                data-show-refresh="true"                                                       
                                data-click-to-select="true">                                                                                                        

                    <!-- <caption>List of users</caption> -->
                    <thead class="thead-dark">
                            <tr>
                            <th data-field="Client_ID" data-visible="false">Client_ID </th>
                            <th data-field="Salutation" data-sortable="true">Title</th>
                            <th data-field="FirstName" data-sortable="true">First Name</th>
                            <th data-field="Surname" data-sortable="true">Surname</th>
                            <th data-field="Tel" data-sortable="true">Tel</th>
                            <th data-field="Email" data-sortable="true">Email Address</th>
                            </tr>
                                </thead>
                                <tbody>
                                <tr>
                                <th scope="row">1</th>
                                <td>Mark</td>
                                <td>Otto</td>
                                <td>@mdo</td>
                                <td>other content</td>
                                <span class="spanEdit"style="display: none;" id="desc3">
                                            <div id="expanderWrap" class="ExpanderWrap"><h4>Description:</h4>
                                            <br>
                                            <div id="expanderContainer" class+"expContainer">
                                            This is row with id=0, containing other content
                                            <p>I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. So when you get something that has the name Kanye West on it, it’s supposed to be pushing the furthest possibilities. I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus.</p>
                                        </div>
                                    </div>
                                </span>
                                </tr>
								 <tr>
                                <th scope="row">2</th>
                                <td>Mark2</td>
                                <td>Otto2</td>
                                <td>@mdo2</td>
                                <td>other content2</td>
                                <span class="spanEdit"style="display: none;" id="desc3">
                                            <div id="expanderWrap" class="ExpanderWrap"><h4>Description:</h4>
                                            <br>
                                            <div id="expanderContainer" class+"expContainer">
                                            This is row with id=0, containing other content
                                            <p>I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. So when you get something that has the name Kanye West on it, it’s supposed to be pushing the furthest possibilities. I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus.</p>
                                        </div>
                                    </div>
                                </span>
                                </tr>
                            </tbody>
                        </table>
                            </div>
                                </div>
                                    </div>
                                        <div class="tab-pane" id="messages" role="tabpanel">
                                            <p>I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at. So when you get something that has the name Kanye West on it, it’s supposed to be pushing the furthest possibilities. I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus.</p>
                                        </div>
                                        <div class="tab-pane" id="settings" role="tabpanel">
                                            <p>
                                            "I will be the leader of a company that ends up being worth billions of dollars, because I got the answers. I understand culture. I am the nucleus. I think that’s a responsibility that I have, to push possibilities, to show people, this is the level that things could be at."
                                            </p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            </div>
                            <button id="myBtn">Expand Rows</button>							
							<script>
							    $('tr').on('click',function(){
								 
								$(this).addClass('collapse');
								});

                                $('#myBtn').on('click',function(){
								  $('tr').removeClass( "collapse" );
								});
							
							</script>
</body>
</html>

Open in new window

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Leonidas DosasCommented:
PS
If you want to check if the tr elements has the collapse name class additionally you can  add this script:
if($('tr').className!=='collapse'){
   $('tr').addClass('collapse');
}

Open in new window

Vijaya KumarCommented:
Hi just go through this tutorial,

This is widely used JS plugin

[https://datatables.net/]
martmacAuthor Commented:
Thanks that's really helpful
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.