Let's say there is a table:
<table id="tblPotrawySkladniki">
<tbody>
<tr><td>banana</td><td>10</td></tr>
<tr><td>orange</td><td>20</td></tr>
<tr><td>raspberry</td><td>20</td></tr>
</tbody>
</table>
I would like to remove entire row where i.e. cell1 = orange. How can I do this using jquery?
CodePudding user response:
Consider the following two examples. Example 1:
$(function() {
$("#tblPotrawySkladniki > tbody td").each(function(i, el) {
if ($(el).text() === "orange") {
$(el).parent().remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblPotrawySkladniki">
<tbody>
<tr>
<td>banana</td>
<td>10</td>
</tr>
<tr>
<td>orange</td>
<td>20</td>
</tr>
<tr>
<td>raspberry</td>
<td>20</td>
</tr>
</tbody>
</table>
This first example gives you more control over how you compare or seek out the cell. For example, you could use:
$(el).text().trim().toLowerCase() === "orange"
This would help ensure a case insensitive search.
Example 2:
$(function() {
$("#tblPotrawySkladniki > tbody td:contains('orange')").parent().remove();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblPotrawySkladniki">
<tbody>
<tr>
<td>banana</td>
<td>10</td>
</tr>
<tr>
<td>orange</td>
<td>20</td>
</tr>
<tr>
<td>raspberry</td>
<td>20</td>
</tr>
</tbody>
</table>
The second example relies on the selector and if they do not match exactly, will not find it. It's quick and uses less lines, yet may not always find the needle.
Each of these, in their own way, will target the Cell and remove the parent Row. See More:
CodePudding user response:
Here is a dynamic way of doing it. For example, enter Orange or Raspberry into the input and click enter.
$(function() {
$("#inputSearch").on('change', function(){
var v = $(this).val();
$('#tblPotrawySkladniki tr td').filter(function() {
if ($(this).text() === v) {
return true;
}
}).parent().remove();
});
})
table {
margin: 0 auto;
}
tr {
border: 1px solid black;
}
tbody {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="inputSearch">Search Value:</label>
<input type="text" name="inputSearch" id="inputSearch">
<table id="tblPotrawySkladniki">
<tbody>
<tr><td>banana</td><td>10</td></tr>
<tr><td>orange</td><td>20</td></tr>
<tr><td>raspberry</td><td>20</td></tr>
</tbody>
</table>