Chirag Shah Chirag Shah - 1 month ago 22
jQuery Question

Jquery Toggle with rowspan attribute

Trying to toggle for each 2nd row means class name = readdetail, but seems its break next row due to first row has attribute rowspan.

What can I do?Any alternative solution ?
How can I show each 2nd row when user click on Toggle button , without affect first row's rowspan attribute.

My html table structure is :



jQuery(document).ready(function() {
jQuery('#btnAdd').on('click', function(e) {
jQuery('.readdetail').toggle();
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAdd" name="btnAdd" class="span1">Toggle</button>
<br/>
<br/>
<table border="1">
<tr>
<th>Sr No</th>
<th>Student Name</th>
<th>Classname</th>
<th>Action</th>
</tr>
<tr class="boxdetail">
<td rowspan="2">1</td>
<td>Test1</td>
<td>Class1</td>
<td rowspan="2">Cancel</td>
</tr>
<tr class="readdetail">
<td>87</td>
<td>90</td>
</tr>
<tr class="boxdetail">
<td rowspan="2">1</td>
<td>Test2</td>
<td>Class2</td>
<td rowspan="2">Cancel</td>
</tr>
<tr class="readdetail">
<td>44</td>
<td>54</td>
</tr>
<tr class="boxdetail">
<td rowspan="2">1</td>
<td>Test3</td>
<td>Class3</td>
<td rowspan="2">Cancel</td>
</tr>
<tr class="readdetail">
<td>84</td>
<td>72</td>
</tr>
</table>




Answer

Try this code. I am adding a class to td with rowspan=2. Now handling the rowspan attribute based on the visibility of other tr

jQuery(document).ready(function() {
    $("td[rowspan='2']").addClass("toggleRowSpan");
    jQuery('#btnAdd').on('click', function(e) {
        jQuery('.readdetail').toggle();
        if($(".readdetail:visible").length==0){
           $(".toggleRowSpan").attr("rowSpan", "1");
        }
        else{
           $(".toggleRowSpan").attr("rowSpan", "2");
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnAdd" name="btnAdd" class="span1">Toggle</button>
<br/>
<br/>
<table border="1">
    <tr>
        <th>Sr No</th>
        <th>Student Name</th>
        <th>Classname</th>
        <th>Action</th>
    </tr>
    <tr class="boxdetail">
        <td rowspan="2">1</td>
        <td>Test1</td>
        <td>Class1</td>
        <td rowspan="2">Cancel</td>
    </tr>
    <tr class="readdetail">
        <td>87</td>
        <td>90</td>
    </tr>
    <tr class="boxdetail">
        <td rowspan="2">1</td>
        <td>Test2</td>
        <td>Class2</td>
        <td rowspan="2">Cancel</td>
    </tr>
    <tr class="readdetail">
        <td>44</td>
        <td>54</td>
    </tr>
    <tr class="boxdetail">
        <td rowspan="2">1</td>
        <td>Test3</td>
        <td>Class3</td>
        <td rowspan="2">Cancel</td>
    </tr>
    <tr class="readdetail">
        <td>84</td>
        <td>72</td>
    </tr>
</table>