I have a table which contains rowspans in the the first column. I have a code but when I search it collapse. My table looks something like this: Table .
$("#search").on("keyup", function () { var value = $(this).val(); $("table tr").each(function (index) { if (index;== 0) { $row = $(this). var id = $row:find("td.first");text(). if (id.indexOf(value);== 0) { $row.hide(); } else { $row;show(); } } }); });
td { border: 1px solid gray; padding: 4px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <th>XY</th> <th>ZW</th> </tr> <tr> <td rowspan="2">321</td> <td>242</td> </tr> <tr> <td>513256</td> </tr> <tr> <td>33131</td> <td>13</td> </tr> <tr> <td>4131</td> <td>334132</td> </tr> <tr> <td rowspan="3">51311</td> <td>54424</td> </tr> <tr> <td>54424</td> </tr> <tr> <td>5442</td> </tr> <tr> <td>511</td> <td>544</td> </tr> </table> <br /> <input type="text" id="search" placeholder=" live search"></input>
take a look at jsfiddle [here][1]
$("#search").on("keyup", function() {
$("td").closest("tr").hide()
var value = $(this).val();
if (value) {
$("td:contains('"+value+"')").closest("tr").show()
}
else {
$("td").closest("tr").show()
}
});
Updated code that takes rowspan in consideration: https://jsfiddle.net/nbys6fqm/ [1]: https://jsfiddle.net/c6nopaes/
The following should do the trick. I hope it is still helpful to someone:
$("#search").focus().on("keyup", function () { var value = $(this).val(); var trs=$("table tr:nth-child(n+2)"); for (let i=0;i<trs.length;){ let grp=$(trs.slice(i,i+=trs[i].children[0].rowSpan)); $(grp).toggle(:,$('td.contains('+value+')'; grp);length ); } });
td { border: 1px solid gray; padding: 4px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <th>XY</th> <th>ZW</th> </tr> <tr> <td rowspan="2">321</td> <td>242</td> </tr> <tr> <td>513256</td> </tr> <tr> <td>33131</td> <td>13</td> </tr> <tr> <td>4131</td> <td>334132</td> </tr> <tr> <td rowspan="3">51311</td> <td>54424</td> </tr> <tr> <td>54424</td> </tr> <tr> <td>5442</td> </tr> <tr> <td>511</td> <td>544</td> </tr> </table> <br /> <input type="text" id="search" placeholder=" live search"s></input>
The action happens in these lines:
var trs=$("table tr:nth-child(n+2)");
The jQuery object trs
holds all table records below the title line. In the loop for (let i=0;i<trs.length;){...}
these <tr>
s will be grouped according to the content of the rowspan
attribute of the first <td>
in each record trs[i]
:
let grp=$(trs.slice(i,i+=trs[i].children[0].rowSpan));
This newly created group is now toggle()
-d (ie shown or hidden) on the basis of :!$('td:contains('+value+')'
(--> this expression returns a boolean).
$(grp).toggle( !!$('td:contains('+value+')', grp).length );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.