FrenkyB
FrenkyB

Reputation: 7197

JQuery html table search by many attributes

I would like to search by three attributes on each row.

I am able to search by one attribute, like this:

var rows = $("#tbl1 > tbody > tr[cName=1]");  

But this throws error:

var rows = $("#tbl1 > tbody > tr[cName=1,cLastN=2]"); 

How to search by all three attributes?

$("#btn1").click(function(){
  debugger;
  var rows = $("#tbl1 > tbody > tr[cName=1]");    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='tbl1' >
  <thead>
    <tr>
      <th>Number</th>
      <th>Name</th>
      <th>Last name</th>
    </tr>
  </thead>
  <tbody>
    <tr cName='1' cLastN='2' cMiddleN='3'>
      <td>1</td>
      <td>John</td>
      <td>Smith</td>
    </tr>
      <tr cName='2' cLastN='2' cMiddleN='4'>
      <td>1</td>
      <td>John</td>
      <td>Smith</td>
    </tr>
      <tr cName='5' cLastN='7' cMiddleN='3'>
      <td>1</td>
      <td>John</td>
      <td>Smith</td>
    </tr>
    
    
  </tbody>
  
  
</table>

<br/>
<br/>
<button id="btn1">Search</button>

Upvotes: 2

Views: 35

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337580

.You need to include the attribute selectors separately, depending on your requirement. If you want to select any element with either attribute (ie. OR logic) use this:

var rows = $('#tbl1 > tbody > tr[cName="1"], #tbl1 > tbody > tr[cLastN="2"]'); 

Whereas if you want elements with both attributes (ie. AND), use this:

var rows = $('#tbl1 > tbody > tr[cName="1"][cLastN="2"]'); 

Also be aware that you're using completely non-standard attributes which can cause issues with JS. I'd suggest changing them to data-* attributes instead.

Upvotes: 1

Ken
Ken

Reputation: 4887

You can use commas (,) to perfom OR selectors

$("#btn1").click(function(){
  debugger;
  var rows = $("#tbl1 > tbody > tr[cName=1]  , #tbl1 > tbody > tr[cName=2], #tbl1 > tbody > tr[cName=3]"); 
  console.log(rows)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='tbl1' >
  <thead>
    <tr>
      <th>Number</th>
      <th>Name</th>
      <th>Last name</th>
    </tr>
  </thead>
  <tbody>
    <tr cName='1' cLastN='2' cMiddleN='3'>
      <td>1</td>
      <td>John</td>
      <td>Smith</td>
    </tr>
      <tr cName='2' cLastN='2' cMiddleN='4'>
      <td>1</td>
      <td>John</td>
      <td>Smith</td>
    </tr>
      <tr cName='5' cLastN='7' cMiddleN='3'>
      <td>1</td>
      <td>John</td>
      <td>Smith</td>
    </tr>
    
    
  </tbody>
  
  
</table>

<br/>
<br/>
<button id="btn1">Search</button>

Upvotes: 1

Related Questions