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

Transforming nested tables into JSON format

I have a table that is dynamically generated and I am looking to convert it into JSON format. Despite trying several methods, I haven't been successful. Can someone help me by providing guidance on how to achieve this using jQuery? For your reference ...

Versatile accordion with separate functionalities for items and panels

When I have different functions for clicking on item and title, clicking on the item works fine but clicking on the panel triggers both functions. Is there a way to resolve this so that I can click on the item using Function_1 and click on the panel using ...

Implementing dynamic data binding in JavaScript templates

I've been experimenting with jQuery and templates, and I managed to create a basic template binding system: <script type="text/template" id="Template"> <div>{0}</div> </script> Furthermore... var buffer = ''; v ...

What causes jquery to not trigger PHP when the HTML file resides in a different location?

In my project structure, I have a 'js' folder containing the jQuery function and a PHP script. The HTML file is located in a separate folder. Currently, the setup looks like this: /server/js/global.js /server/js/script.php /server/html/stude ...

A fragmented rendering of a gallery featuring a CSS dropdown menu

Hey there! I'm a newbie coder seeking some assistance. Recently, I stumbled upon a tutorial online that taught me how to create a drop-down menu. However, whenever I hover over "Gallery" on my website, things go haywire and the layout gets all messed ...

Encountering the "Local resource can't be loaded" error when attempting to link a MediaSource object as the content for an HTML5 video tag

I'm attempting to make this specific example function properly. Everything runs smoothly when I click the link, but I encounter an error when trying to download the HTML file onto my local machine and repeat the process. An error message pops up sayi ...

In jQuery, conditionally nest divs within another div based on a specific requirement

There is a container with multiple nested elements that need to be rearranged based on the value of their custom attribute. The goal is to reorder those elements at the end of the container if their 'data-keep-down' attribute is set to true, usin ...

Attempting to divide the main page into quadrants

I want to split my homepage into four equal images without any scrolling. When you click on the website, I want the four images to expand and cover the entire screen with no scrollbars. I've made some progress with my code, but it's not quite the ...

Incorporate ng-model to manage dynamically generated HTML elements

I have created dynamic div elements with a button inside, and I want to access its value using ng-model, but the value is not being retrieved. Here is my code: var url = "/api/chatBot/chatBot"; $http.post(url,data) .success(function(data){ $scope.mes ...

Troubleshooting Jqgrid Keyboard Navigation Problem

Here is a link to the jsfiddle code snippet. Upon adding jQuery("#grid").jqGrid('sortableRows'); into my JavaScript code, I encountered an issue where keyboard navigation no longer worked after sorting rows Below is the JavaScript code snippet: ...

When using the POST method to modify data via an HTML form, the previous values may be

I am currently developing a CRUD system and focusing on the Update functionality. My task involves updating existing user data with new information submitted through an HTML form. At this stage, I am working on retrieving the POST values from the HTML for ...

Incorporating input fields into an HTML form

I'm looking to enhance my form by adding input fields dynamically through the JavaScript function when I click on the add button: let i = 0; function increment() { i += 1; } function addFieldFunction() { let newDiv = document.createElement(&apos ...

What is the best way to pass the text of a selected option in a dropdown menu to a function when a button is clicked in AngularJS?

Alright, so I've got this HTML page with a select element. The select has three options defined in the $scope below: <div id="mainID" ng-controller="theController"> <form name="assetTypeForm" class="form-horizontal" role="form" novalidat ...

Display only the div on an iPad screen

Is there a way to show this DIV only on an iPad screen? I've looked around on Google for solutions, but none of them seem to work. It always ends up displaying on my computer as well. Is it possible to make it show only on an iPad screen? @media only ...

Utilizing CSS classes based on subelements

I need to assign css classes to items in a list based on certain criteria. Here is an example of the structure I am working with: <ul ng-controller="Navigation"> <li><a href="#">Category A</a> <ul> < ...

Exploring the implementation of the meta robots tag within Joomla 2.5's global settings

Encountering a peculiar issue with Joomla 2.5 and the Meta robots tag. Joomla seems to have a flaw where regardless of the URL, as long as there is a valid article id, it will generate a page. For instance: The id '61' is valid but leads to a ...

The functionality of using an Ajax call to invoke a php function on the same page is not functioning correctly

I am facing an issue where Ajax is not working in the same PHP file as the PHP function I want to call. My goal is to have a button that, when pressed, will trigger the function without reloading the page. I have placed my Ajax script at the bottom and the ...

Is it possible for a user to chat on Whatsapp by entering their mobile number in an HTML form within the app?

<?php require_once('./database.php'); if(isset($_REQUEST['submit1'])) { $number = $_REQUEST['whatsappnumber']; $code = $_REQUEST['countorycode']; $sql = "INSERT INTO whatsapp (whatsappnumber,counto ...

align-content and justify-content in flexbox are not producing the desired results

align-content and justify-content don't appear to be working when I test them in both Chrome and Firefox. I'm puzzled as to why they're not functioning as expected. #container { display: flex; flex-wrap: wrap; justify-content: cent ...

Adjust the image size to fit the page according to its height

Having a dilemma here. I have this square image (2048x2048) that I want to set as a background. The tricky part is, I want it to display borders when the page stretches into widescreen mode, but also resize while maintaining its square shape when the page ...