James
James

Reputation: 2246

Remove a row from Html table based on condition

I have a html table

<TABLE id="dlStdFeature" Width="300" Runat="server" CellSpacing="0" CellPadding="0">
  <TR>
    <TD id="stdfeaturetd" vAlign="top" width="350" runat="server"></TD>
  </TR>
</TABLE>

I am dynamically adding values to it as :

function AddToTable(tblID, value)
{
    var $jAdd = jQuery.noConflict();

    var row= $jAdd("<tr/>").attr("className","lineHeight");
    var cell = $jAdd("<td/>").attr({"align" : "center","width" : "3%"});
    var cell1 = $jAdd("<td/>").html("<b>* </b>" + value);
    row.append(cell);
    row.append(cell1);
    $jAdd(tblID).append(row);
}

Now I want a function to remove a row from this table if the value matches..as

function RemoveFromTable(tblID, VALUE)
{
   If(row value = VALUE)
   {
     remove this row
   }
}

Here VALUE is TEXT ..which needs to be matched..If exists need to remove that row,,

Upvotes: 0

Views: 4784

Answers (5)

Dilip Kumar Choudhary
Dilip Kumar Choudhary

Reputation: 469

Remove row from HTML table that doesn't contains specific text or string using jquery.

Note: If there are only two column in HTML table, we can use "last-child" attribute to find.

*$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
    var lastTD = $(this).find("td:last-child");
    var lastTdText = lastTD.text().trim();
    if(!lastTdText.includes("DrivePilot")){
        $(this).remove();
    }
});

});

Note: If there are more than two column in HTML table, we can use "nth-child(2)" attribute to find.

Passing column index with "nth-child(column index)"

$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
    var lastTD = $(this).find("td:nth-child(2)");
    var lastTdText = lastTD.text().trim();
    if(!lastTdText.includes("DrivePilot")){
        $(this).remove();
    }
});

});

Note: "DrivePilot" is nothing but text or string

Upvotes: 0

muneebShabbir
muneebShabbir

Reputation: 2528

try this

function RemoveFromTable(tblID, VALUE){
   $("#"+tblID).find("td:contains('"+VALUE+"')").closest('tr').remove();
}

hope it will work

Upvotes: 5

Adil Shaikh
Adil Shaikh

Reputation: 44740

function RemoveFromTable(tblID, VALUE){
   $(tblID).find('td').filter(function(){
     return $.trim($(this).text()) === VALUE;
   }).closest('tr').remove();
}

Upvotes: 0

Rob
Rob

Reputation: 11788

I highly recommend using a ViewModel in your case. So you can dynamically bind your data to a table and conditionally format it to whatever you like. Take a look at Knockout.js: http://knockoutjs.com/

Upvotes: 0

GautamD31
GautamD31

Reputation: 28763

Try like this

function RemoveFromTable(tblID, VALUE)
{
   If(row value = VALUE)
   {
      $("TR[id="+VALUE+"]").hide();  //Assumes that VALUE is the id of tr which you want to remove it
   }
}

You can also .remove() like

$("TR[id="+VALUE+"]").remove();

Upvotes: 0

Related Questions