I have a table which have some rows collapsible. When I click any rows, all table collapsed.(except first row)
But I want to collapse all table when just I click first row. So the other rows will not collaps the table.
Here is my code:
<table id="customers2" style="width:100%" onclick="expandCollapseTable(this)">
//first row
<tr class="gradient">
<th style="width:60%">Fruits</th>
<th style="width:40%">Value</th>
</tr>
//second row
<tr style="display:none">
<td>Apple</td>
<td>10</td>
</tr>
//third row
<tr style="display:none">
<td>Orange</td>
<td>20</td>
</tr>
</table>
Here is my JS code:
<script type="text/javascript">
function expandCollapseTable(tableObj)
{
var rowCount = tableObj.rows.length;
for(var row=1; row<rowCount; row++)
{
rowObj = tableObj.rows[row];
rowObj.style.display = (rowObj.style.display=='none') ? '' : 'none';
}
return;
}
</script>
2
Answers
I modify your function to this;
In this function, we’re getting the first row of the table using
tableObj.rows[0]
. Then, we’re checking if the display style of this row is ‘none’. If it is, we’re setting it to an empty string to make it visible. If it’s not ‘none’, we’re setting it to ‘none’ to hide it.This way, when you click on the first row, the table will collapse or expand. However, when you click on the other rows, nothing will happen because this function isn’t attached to them.
I also modify you html to this;
As you notice, I’ve moved the
onclick
attribute from thetable
element to thetr
element of the first row. Now, theexpandCollapseTable
function will be called when you click on the first row, but not when you click on the other rows.Modified Code
-html
-javascript
I think in you function, it’s not good to loop every tr.
And also your first row is maybe heading.
So you have to seperate your first with body like I did.
Ok?