Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering by data attribute

I'm trying to use filter to find table rows that contain particular values in two different data attributes (in addition to general text).

I can't seem to properly read the values from the two data attributes. Outputting the values (licData and stateData) to the console show 'undefined'. And, of course, the search fails.

JS

var $rows = $('.livesearch tr');

$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

  $rows.show().filter(function() {

    var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
    var licData = $(this).find('td').attr('data-lic');
    var stateData = $(this).find('td').attr('data-state');

    console.log(text + '-' + licData + '-' + stateData + '<br>');

    if (!~stateData.indexOf(val) || !~licData.indexOf(val) || !~text.indexOf(val)) {
      return true;
    } else {
      return false
    }

  }).hide();
});

SAMPLE TABLE ROW

<tr>
  <td>Aaron</td>
  <td>Ellebrach</td>
  <td>Clerical</td>
  <td>444-444-4444</td>
  <td>Call</td>
  <td data-lic="special">C</td>
  <td data-state="state data here">CA</td>
</tr>  
like image 572
Doug Avatar asked Dec 09 '25 05:12

Doug


1 Answers

Try:

var licData = $(this).find('td[data-lic]').attr('data-lic');
var stateData = $(this).find('td[data-state]').attr('data-state');

Your code:

$(this).find('td').attr('data-lic')

actually gives you the attribute of the first td which is obviously undefined, but when you do $(this).find('td[data-lic]') you are actually looking for any td with this data attribute present and hence you get the values like:-

var licData = $('tr').find('td[data-lic]').attr('data-lic');
var stateData = $('tr').find('td[data-state]').attr('data-state');
console.log('licData:   ' + licData);
console.log('stateData: ' + stateData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<table>
  <tr>
    <td>Aaron</td>
    <td>Ellebrach</td>
    <td>Clerical</td>
    <td>444-444-4444</td>
    <td>Call</td>
    <td data-lic="special">C</td>
    <td data-state="state data here">CA</td>
  </tr>
</table>
like image 166
palaѕн Avatar answered Dec 10 '25 20:12

palaѕн



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!