BurebistaRuler
BurebistaRuler

Reputation: 6519

Table string compare using jQuery or JavaScript

How can I compare data from two tables using native JavaScript or jQuery? For example I have two tables in the same HTML page and I want to compare few columns from those tables. For example: column "username" contains some id's in both table and I want to highlight those "username" cells that doesn't have the same id on "username" columns where "first name" and "last name" columns cells are identical.

here is a small fiddle

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
    <table class="table">
      <caption>Table One</caption>
      <thead>
        <tr>
          <th>#</th>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Username</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th scope="row">1</th>
          <td>Mark</td>
          <td>Otto</td>
          <td>7872</td>
        </tr>
        <tr>
          <th scope="row">2</th>
          <td>Jacob</td>
          <td>Thornton</td>
          <td>9890</td>
        </tr>
        <tr>
          <th scope="row">3</th>
          <td>Larry</td>
          <td>the Bird</td>
          <td>7719</td>
        </tr>
      </tbody>
    </table>
</div>

<div class="container">
    <table class="table">
      <caption>Table Two</caption>
      <thead>
        <tr>
          <th>#</th>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Username</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <th scope="row">1</th>
          <td>Mark</td>
          <td>Otto</td>
          <td>7872</td>
        </tr>
        <tr>
          <th scope="row">2</th>
          <td>Jacob</td>
          <td>Thornton</td>
          <td>2232</td>
        </tr>
        <tr>
          <th scope="row">3</th>
          <td>Larry</td>
          <td>the Bird</td>
          <td>7719</td>
        </tr>
      </tbody>
    </table>
</div>

Upvotes: 3

Views: 1008

Answers (1)

LTasty
LTasty

Reputation: 2008

You need to each the table and check if cells are differents

$(".table:first tbody tr").each(function(){
    var tabletr=$(this);
    var tableone=$(this).children("td");
    $(".table:last tbody tr").each(function(){
        if(tableone.eq(0).text()== $(this).children("td").eq(0).text() && tableone.eq(1).text()== $(this).children("td").eq(1).text() && tableone.eq(2).text()!= $(this).children("td").eq(2).text()){
            tabletr.css("background","#f00");
            $(this).css("background","#f00");
        console.log("USERNAME DIFFERENT!"+$(this).children("td").eq(2).text());
        }
    });
});

https://jsfiddle.net/DTcHh/11529/

Upvotes: 3

Related Questions