Locate an element by filtering and finding two distinct values using the .eq() method

I need help filtering a table row based on the values in two different columns. The idea is to show only the row where one column has "value1" and another column has "value2", while hiding all other rows. If none of the rows meet this condition, then hide them all.

Below is the jQuery code I have tried so far:

var firstDropVal = $('#first .fstselected').text(); // Value from the first dropdown
var secondDropVal = $('#second .fstselected').text(); // Value from the second dropdown

// 'rows' is the class of the table rows (tr)
var $rowsNo = $('.rows').filter(function() {
  return $.trim($(this).find('td:visible').eq(0 && 1).text()) !== firstDropVal && secondDropVal
}).hide();

This is the HTML code for my table:

while($row = mysqli_fetch_array($result)) {

$i++;

 echo "
<tr class='rows' id='rows".$i."'>
<td name='rows".$i."' id='hersteller".$i."' class='text-left'>".$row['Hersteller']."</td>
<td id='artikel".$i."' class='text-left'>".$row['Artikel']."</td>
<td id='mase".$i."' class='text-left'>".$row['Mase']."</td>
<td id='stuecke".$i."' class='text-left'>".$row['Stuecke']."</td>
<td id='herstellerkurz".$i."' class='text-left'>".$row['HerstellerKurz']."</td>
<td id='masekurz".$i."' class='text-left'>".$row['MaseKurz']."</td>
<td id='farbekurz".$i."' class='text-left'>".$row['FarbeKurz']."</td>
<td id='artikelnummer".$i."' class='text-left'>".$row['Artikelnummer']."</td>
</tr>

 "; 

Answer №1

To simplify the sample, I opted to create a table with only 2 columns. You have the option to hide() all rows and then filter() based on dropdown selection.

$(".filter").change(function() {
  var color = $("#filter-color").val().trim();
  var number = $("#filter-number").val().trim();

  $(".row").hide().filter(function() {
    return (
      color === "" ||
      color === $(this).find("td:eq(0)").text().trim()
    ) && (
      number === "" ||
      number === $(this).find("td:eq(1)").text().trim()
    )
  }).show();

});
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, tr {
  border : 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
FILTER:

<select id="filter-color" class="filter">
  <option value=""></option>
  <option value="red">red</option>
  <option value="green">green</option>
  <option value="blue">blue</option>
</select>

<select id="filter-number" class="filter">
  <option value=""></option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<hr />

<table>
  <tr>
    <th>Color</th>
    <th>Number</th>
  </tr>
  <tr class="row">
    <td>red</td>
    <td>2</td>
  </tr>
  <tr class="row">
    <td>green</td>
    <td>1</td>
  </tr>
  <tr class="row">
    <td>blue</td>
    <td>3</td>
  </tr>
  <tr class="row">
    <td>red</td>
    <td>3</td>
  </tr>
  <tr class="row">
    <td>blue</td>
    <td>2</td>
  </tr>
  <tr class="row">
    <td>green</td>
    <td>1</td>
  </tr>
</table>


Alternatively, you can utilize the every() method to check the array values for precise filtering.

$(".filter").change(function() {

  var filters = [                    //Store filter values in an array format to match table data order
    $("#filter-color").val().trim(),
    $("#filter-number").val().trim()
  ];

  $(".row").hide().filter(function() {
    return $(this).find("td").get().every(function(o, i) {
      return $(o).text().trim() === filters[i] || filters[i] == "";
    });
  }).show();

});
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
tr {
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
FILTER:

<select id="filter-color" class="filter">
  <option value=""></option>
  <option value="red">red</option>
  <option value="green">green</option>
  <option value="blue">blue</option>
</select>

<select id="filter-number" class="filter">
  <option value=""></option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

<hr />

<table>
  <tr>
    <th>Color</th>
    <th>Number</th>
  </tr>
  <tr class="row">
    <td>red</td>
    <td>2</td>
  </tr>
  <tr class="row">
    <td>green</td>
    <td>1</td>
  </tr>
  <tr class="row">
    <td>blue</td>
    <td>3</td>
  </tr>
  <tr class="row">
    <td>red</td>
    <td>3</td>
  </tr>
  <tr class="row">
    <td>blue</td>
    <td>2</td>
  </tr>
  <tr class="row">
    <td>green</td>
    <td>1</td>
  </tr>
</table>

Answer №2

It seems like the approach you're taking with these functions is not yielding the desired results.

.eq(0 && 1)
firstDropVal && secondDropVal

This issue stems from operator precedence, which you can read more about here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

To address this, you will need to conduct four separate tests (though there are alternative methods, this is essentially what you'll be doing).

return 
    $.trim($(this).find('td:visible').eq(0).text()) === firstDropVal
    || $.trim($(this).find('td:visible').eq(1).text()) === secondDropVal
    || $.trim($(this).find('td:visible').eq(0).text()) === firstDropVal
    || $.trim($(this).find('td:visible').eq(1).text()) === secondDropVal

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Setting the width of colspan elements can be challenging when other columns have dynamic widths

I am working with a table setup that includes various columns for data tracking: <table > <thead style="width: calc(100% - 15px); display: table; table-layout: fixed;"> <tr> <th colspan="3">& ...

Next.js is constantly encountering an issue where it throws an error stating "params

I've managed to establish a successful connection between my custom server using Node.js and Express.js with Next.js. The issue I'm facing is when trying to fetch a specific car by its id upon clicking it among other cars, as I keep encountering ...

Interceptors in axios do not trigger when making requests through a PHP proxy

I am currently working on a React app that will be interacting with services hosted on a remote server. During development on my local machine using the react-scripts server at localhost:3000, I disable CORS in the browser and have no issues with axios f ...

Resetting the positions of images can be done by following these

I'm currently in the process of developing a game and need assistance with implementing a game end function. Can you provide guidance on how to reset all images back to their original positions? ...

The destroy method of Chart.js does not appear to have any impact on the

Hello, I've come across this issue in my react app that I need help with: this.chart = new Chart(node, options); // adding data to the chart ... this.chart.destroy(); this.chart = null; this.chart = new Chart(node, options); // adding data to the cha ...

Why is it that masonry is typically arranged in a single column with overlapping

I have been using the appended function in my code to add elements to a masonry instance that has already been initialized. However, I am facing an issue where all the tiles are being laid out in a single column and some of them are overlapping each oth ...

Constructing markup for text and subtext in a meaningful manner

I am in the process of creating a roster of Employees and their dependents on a webpage and I could use some guidance on the best way to structure this information. Here is an example of the content on my page: <div> John Smith Employee - 03/01/198 ...

Updating an element in jQuery using the .each() method

HTML code: var values=[5, 10, 15, 20, 25, 30] $.each(values, function(position, number) { setTimeout(function() { $('#contentBox').text(number); }, position * 5000 ); }); I am attempting to update the content of the contentBox d ...

Transitioning between javascript functions

Having some issues with a switch case statement, also tried using if-else but no luck. In the HTML code: <select onBlur="functionCalc()" id="art"> <option value="hours" id="hours">Hours</option> <option value="minutes" id="mins">M ...

Vuejs is throwing an error claiming that a property is undefined, even though the

I have created a Vue component that displays server connection data in a simple format: <template> <div class="container"> <div class="row"> <div class="col-xs-12"> <div class="page-header"> < ...

JavaScript: Leveraging arrays as key values

Is there a way in javascript to create an Object with keys as numbers and values as arrays of objects? I am aiming to generate an object structured like this: {Key: "1", value: [Object, Object, ...], key: "2", value: [Object, Object, ...], key:"N", value ...

Is the ajax success function failing to work properly in JavaScript?

Although I've searched extensively on Stack Overflow, none of the similar questions seem to solve my issue. The problem I'm facing is that the success function is not triggering the alert message and I can't seem to figure out why. <form ...

You cannot use css() in conjunction with appendTo()

$('#item').click(function() { $.ajax({ url: 'server.php', type: 'POST', data : {temp : 'aValue'}, success: function(data) { $(data).css('color&apo ...

Using Axios to fetch data and populating select dropdown options in a Vue component

I am currently working on integrating the response data values with my multiselect options. Although the console log displays the returned results, I'm facing difficulty in connecting them to my multiselect options. When I enter 'Day' into ...

` Time Running Out: A Classy Countdown Timer`

Here are the lines of code I have included in my webpage - example/demo. HTML: <p class="countdown-timer">10:00</p> <p class="countdown-timer">10:00</p> JavaScript: I am looking for guidance as a beginner in JavaScript and JQue ...

SVG to create a gradient mask that appears transparent

I require assistance with working on svg's. I have a "background image" with another "image" layered over it. The "image" needs to have a hole cut out of it so that the background image can shine through. I managed to achieve this by utilizing svg: ...

Error loading CSS file: 'Invalid MIME type detected, expecting text/css'

Can someone please help me figure out why none of the CSS files I linked are loading on my website? It's strange because the CSS for another page on the same site is loading without any issues. My server is built using express and I'm using ejs ...

Using the .slider class on concealed div elements

Explaining this may be a bit tricky, but here we go... I have multiple hidden divs that switch with each other when a link is clicked using $(document).ready(function(){ $('a').click(function () { var divname= this.name; $("#"+divname ...

Guide to dynamically displaying location data using JSON string on Google Maps in ASP.NET

A script is being used to display locations on a Google map: <script type="text/javascript"> $(document).ready(function () { var markersdetails = { "Iran": { "title": "Iran", "lat": "32.000000", ...

The click function is malfunctioning for the second time

Two .click functions are being utilized here - one to add an element (div) to a container, and the other to remove it. The container starts off empty. Strangely, clicking on the function to remove the element doesn't work. $(document).ready(function( ...