Maintaining nth-child(odd) following filtering using jQuery

I am using a jQuery script to filter a table with multiple entries on this site. The filtering works well, but the issue arises when it comes to maintaining the correct tr:nth-child(odd) color that I have specified in my CSS. After filtering, the original color is retained instead of the updated one. To clarify further, refer to the JSFiddle demo link provided at the bottom of the page.

Customized HTML Code:

<input type="text" id="search" placeholder="Search...">
<table id="table">
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Chantal</td>
    <td>37</td>
    <td>Belgium</td>
  </tr>
  <tr>
    <td>Pedro</td>
    <td>31</td>
    <td>Spain</td>
   ...
    </table>

CSS Styles Applied:

#search {
  height: 20px;
  margin: 4px 0;
  padding: 5px 5px;
   />ped: #E5C100;

  border-radius: 5px;
  -moz-border-radius: 5px;
  -webkit-border-radius: 5px;
}

table {
  width: 100%;
  borde ... 
}
  
tr:nth-child(odd) {
  background-color: #E5E5E5;
}

JavaScript (jQuery) Functionality:

var $rows = $('#table tr:not(:first)');
$('#search').keyup(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

    $rows.show().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ')... }).hide();
});

Try out the functionality through the JSFiddle Demo Link provided below:

https://jsfiddle.net/8m6p1k96/

Your assistance is greatly appreciated!

Answer №1

For the latest version of the fiddle, please visit JSFIDDLE or view the snippet below:

The CSS for tr:nth-child(odd) has been removed to accommodate the dynamic nature of the table when using the search filter. To initialize the table with striping, add a CSS class "zebra-stripe". Then, within your keyup function, as the visible rows change, reapply striping by looping through the visible rows and adding the stripe class to every other row. Additionally, remove the stripe class from rows that may have changed positions due to the search filter.

var $rows = $('#table tr:not(:first)');

// Add stripes to odd # rows.. 
$('tr:nth-child(odd)').each(function() {
  $(this).addClass('zebra-stripe');
});

$('#search').keyup(function() {
  var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
  $rows.show().filter(function() {
    var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
    return !~text.indexOf(val);
  }).hide();

  // Re-stripe now visible row set..
  $('#table tr:visible').each(function(e, v) {
    if (e % 2 == 0) {
      $(this).addClass('zebra-stripe');
    } else {
      $(this).removeClass('zebra-stripe');
    }
  });

});
#search {
  height: 20px;
  margin: 4px 0;
  padding: 5px 5px;
  border: 1px solid #E5C100;
  border-radius: 5px;
}

table {
  width: 100%;
  border-collapse: collapse;
  table-layout: fixed;
  margin-top: 2%;
}

th {
  background-color: #CC0000;
  color: #FFFFFF;
  text-align: left;
  padding: 10px;
}

td {
  text-align: left;
  padding: 10px;
}

.zebra-stripe {
  background-color: #E5E5E5;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search" placeholder="Search...">

<table id="table">
  <tr>
    <th>Name</th>
    <th>Age</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Chantal</td>
    <td>37</td>
    <td>Belgium</td>
  </tr>
  <tr>
    <td>Pedro</td>
    <td>31</td>
    <td>Spain</td>
  </tr>
  <tr>
    <td>John</td>
    <td>51</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Vadim</td>
    <td>24</td>
    <td>Romania</td>
  </tr>
  <tr>
    <td>Aleksei</td>
    <td>25</td>
    <td>Russia</td>
  </tr>
  <tr>
    <td>Chantal</td>
    <td>37</td>
    <td>Belgium</td>
  </tr>
  <tr>
    <td>Pedro</td>
    <td>31</td>
    <td>Spain</td>
  </tr>
  <tr>
    <td>John</td>
    <td>51</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Vadim</td>
    <td>24</td>
    <td>Romania</td>
  </tr>
  <tr>
    <td>Aleksei</td>
    <td>25</td>
    <td>Russia</td>
  </tr>
</table>

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 up Datatables using AngularJS

I am working on a controller that organizes song rankings based on sales data. Upon initialization, the controller automatically sends an HTTP GET request to retrieve all the songs needed for display (currently set at the top 20 songs). If I ever need to a ...

Tips for modifying and refreshing data in a live table with JQuery

One challenge I'm facing is figuring out how to transfer the data from a dynamic table back into input fields when clicking on the edit button of a specific row. Additionally, I need to update that particular row based on any changes made to the value ...

What is the functionality of the disabled attribute on an option tag within a dropdown select menu?

I am working with a code snippet that involves understanding how the attribute:disabled functions on an <option> within a <select> element! Let's say I have a dropdown for ratings and I select the 5-star option (★★★★★). Upon sel ...

Prevent divs from jumping to a new line with the float property

I've been busy working on a responsive webpage and so far, everything is going smoothly. The only issue I'm facing is that when the browser window size decreases and reaches a certain point, the div elements jump to the next line. Take a look at ...

The standard color code applied to an HTML button

I need to create an anchor element <a> that resembles an HTML button. However, I am struggling to find the default background color for the input type button. ...

Embedded URL in dynamically created AJAX text

I created a search field that uses ajax/jquery to generate a list of users. Result: <li class="list-group-item"> <span class="glyphicon glyphicon-user"></span> <span class="badge addUserToGroup" data-user="{{ user.getId }}"&g ...

What is the proper way to credit the glyphicons element in Twitter's bootstrap framework?

According to the section on icons in the Base CSS page of GitHub's Twitter bootstrap, Glyphicons Halflings were not originally available for free. However, thanks to an agreement between Bootstrap and the creators of Glyphicons, developers can now use ...

Interactivity with SVG clip-path featuring multiple paths through hover events

I have a unique SVG demo image with multiple circles that are clipping an animated GIF. Can we detect hover events for each individual circle as the user mouses over them? For example, the top-left or middle-right circle? Is it also possible to change th ...

Issue with AngularJS URLs not functioning properly when using HTML5 mode

Utilizing the AngularJS SPA template in Visual Studio. In my app.js file, I have the following code: $stateProvider .state('touranalysis', { url: '/touranalysis', templateUrl: '/views/touranalysis/index', ...

Tips for preventing a React component from scrolling beyond the top of the page

I am looking to achieve a specific behavior with one of my react components when a user scrolls down a page. I want the component to reach the top of the page and stay there without moving any further up. Here is an Imgur link to the 'intranet' ...

The concept of Theme.breakpoints does not exist in MUI React, there is

I keep running into the same error where theme.breakpoints is undefined when I try to use theme.breakpoints.up in my code. The versions of the dependencies I am currently using are: "@emotion/react": "^11.9.0", "@emotion/styled&quo ...

Activate the preview mode by transmitting information between two controllers

I'm trying to set up a preview mode in one controller to show an image in another controller using an angular service. However, I'm struggling with the final step of getting the URL from the passed parameter into the ng-src in SideMenuCtrl dynami ...

Issues with retrieving data from Firestore and storing it into an array in a React

Struggling to fetch data from my firestore and display it on the webpage. Despite trying all possible solutions and searching extensively, I am unable to get it working. When using the code below, nothing appears on the website. However, if I switch to th ...

Distinguishing CSS Variances on ASP.Net Site with Android 4+

I am encountering an issue with my current ASP.Net Mobile Website design. It is rendering correctly on android phones pre 4, iPhones, and Blackberries. This problem requires a bit of setup to explain... CSS tr { color: #00ff00; } #MasterBackButton { ...

The Bootstrap nav-tab functions perfectly on a local server, but unfortunately does not work when hosted remotely

UPDATE: Issue resolved so I have removed the Github link. It turns out that Github pages require a secure https connection for all linked scripts. Always remember to check the console! I encountered an unusual bug where the Bootstrap nav-tab functionality ...

What is a method to resize an SVG path to a specific pixel size without altering any of the SVG attributes?

Is it possible to adjust the size of a <path> to fit a specific px dimension by simply altering the attributes of the path itself? Within an SVG, I have a carrot symbol represented by a <path>. <svg height="600" width="400"> <p ...

Executing an Ajax form submission in React.js

Currently in the process of developing my initial application using React.js and aiming to send a contact form via email with Ajax. I've been referencing a solution from this source: . Unfortunately, only parts of the full component file are available ...

The QWebview is not rendering the HTML page correctly

I am currently working on a software project that includes a QWebView for displaying HTML files. However, I am facing an issue with the welcome page not displaying correctly. Instead of having an image between the red lines at the center, it appears unusua ...

FormView does not have a defined namespace prefix asp - How should I specify my Page Directive?

After creating a basic web page using Microsoft Expression Web 4 with an ASP Connection to a local Access DB, I encountered an error when navigating to the page from another webpage. The browser displayed the following errors: Error: Namespace p ...

Developing a Form Submission Feature Using JQuery Mobile

I'm having trouble submitting a form using JQuery Mobile. Currently, my code looks like this: <form action="#pagetwo" method="post" name="myform"> <input type="text" name="myname"> <input type="submit" value="submit" /> ... and th ...