VPY
VPY

Reputation: 463

jQuery : hide one column based on another column

I have a simple HTML table containing 3 columns as shown below.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

</style>
</head>
<body>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alpha</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Beta</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  
</table>

</body>
</html>

I would like to hide the 3rd column's value if there is value in 2nd column.

For example in my table (from the code snippet), since both the rows have value in the "Contact" column I want the data from the "Country" column to be hidden.

Is it possible to do this in jQuery ?

Upvotes: 0

Views: 94

Answers (1)

sethuraman
sethuraman

Reputation: 189

Following code will help you on this one

$(document).ready(function(){
    $("table tbody tr").each(function() {
        contact = $.trim($(this).children('td:nth-child(2)').html());
        if (contact) {
            $(this).children('td:nth-child(3)').html('');
        }
    });
});

I have used the pseudo class nth-child, you can also give class name for the td and use it to capture the data inside the cells.

Check the working snippet.

$(document).ready(function(){
    $("table tbody tr").each(function() {
        contact = $.trim($(this).children('td:nth-child(2)').html());
        if (contact) {
            $(this).children('td:nth-child(3)').html('');
        }
    });
});
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<style>
table {
    font-family: arial, sans-serif;
    border-collapse: collapse;
    width: 100%;
}

td, th {
    border: 1px solid #dddddd;
    text-align: left;
    padding: 8px;
}

</style>
</head>
<body>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alpha</td>
    <td>Maria Anders</td>
    <td>Germany</td>
  </tr>
  <tr>
    <td>Beta</td>
    <td>Francisco Chang</td>
    <td>Mexico</td>
  </tr>
    <tr>
    <td>Gamma</td>
    <td></td>
    <td>USA</td>
  </tr>
  
</table>

</body>
</html>

Upvotes: 1

Related Questions