jQuery method for implementing alternating row colors that are not sequential

Starting from scratch here. I've fetched a table from a remote server where odd rows are white and even rows are grey. Some rows have been hidden:

$("td").filter(function(){ return $(this).text()=='R1';}).text('Row1'); //white
$("td").filter(function(){ return $(this).text()=='R2';}).text('Row2'); //grey
$('tr:nth-child(3)').hide();                                            //white
$("td").filter(function(){ return $(this).text()=='R4';}).text('Row4'); //grey
$('tr:nth-child(5)').hide();                                            //white
$("td").filter(function(){ return $(this).text()=='R6';}).text('Row6'); //grey
$("td").filter(function(){ return $(this).text()=='R7';}).text('Row7'); //white

The alternating row pattern is now disrupted, making it white, grey, grey, grey, white. How do I revert to the original alternating colors? Applying a class like:

$("tr").filter(":even").addClass("even");
+ css
tr.even td{background-color: blue;}
results in white, blue, blue, blue, white which still doesn't alternate.

I can achieve this with:

$('tr:nth-child(4)').each(function(i){ $(this).find('td').css('background-color', 'white');});
, making it white, grey, WHITE, grey, white. However, there's an issue! Row 4 contains red cells that should remain red. The previous code turns them white instead.

The style provided by the server is:

<script src="remoteserver/sorttable.js"></script>
<style type = "text/css">';
    td.datacellone{
        background-color: #C0C0C0;
    }
    th.datacellheader{
        background-color: #6A5ACD;
    }
    td.alert{
        background-color: #FF0000;
    }
    td.orange{
        background-color: #FFA500;
    }
    td.green{
        background-color: #008000;
    }
</style>

The goal is to maintain the red alert color while restoring the alternating white and grey rows.

Answer №1

If you have CSS classes named even and odd, you can try out this code snippet:

var $rows = $('tr').removeClass('even odd').filter(':visible');
$rows.filter(':even').addClass('even');
$rows.filter(':odd').addClass('odd');

This code removes any existing even and odd classes from the table rows, then applies the classes only to the visible ones using the :visible selector.

Check out this demo (which also demonstrates that individual cells are not impacted by row classes): http://jsfiddle.net/J5DqP/1/

Answer №2

One straightforward method is to reapply the classes.

 var $table = $('table');
 $('tr:even', $table).addClass('even');
 $('tr:odd', $table).addClass('odd');

  //Remove 1 td

  $('tr', $table).removeClass('even odd'); // Remove both the classes
  $('tr:even', $table).addClass('even');
  $('tr:odd', $table).addClass('odd');

**EDIT**

If you wish to modify the styles being applied, substitute

td.alert{ background-color: #FF0000; }

with

tr td.alert{ background-color: #FF0000; }

OR

tr.odd td.alert, tr.eventd.alert, { background-color: #FF0000; }

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

"The Ajax POST request to MyUrl returned a 404 error, indicating that the resource

While working on my Grails code, I encountered an error when the Ajax function received a response from the controller action. The parameters are being passed successfully by the Ajax function, and the controller function is executed. However, upon return ...

I'm having trouble getting rid of this stubborn loader on the website

I am currently utilizing the following template: . My objective is to eliminate the preloader progress bar that displays the loading progress of the page in percentage. The files associated with this preloader are as follows: Loader CSS File - www[dot]the ...

The functionality of switching between two layouts using a JavaScript button is currently not functioning

My concept involves implementing a switch that alternates between displaying a bootstrap carousel and cards. Essentially, one of them will be visible when the button is pressed while the other remains invisible. Initially, I am attempting to hide my existi ...

The layout of the table is not formatted in a single continuous line

I recently implemented the material-ui table and noticed that the header has a multiline break space. I am looking for a way to make it display in a single line instead. Is there any solution for achieving this using material UI or CSS? Feel free to chec ...

Error message: The object does not have the necessary support for the property or method 'modal'

When attempting to display a modal pop-up to showcase details of a selected record in a grid, I encounter an issue. Despite setting the values for each control in the modal pop-up, it fails to open. I have ensured that all necessary references are included ...

Is it possible to add information to the form data object?

When I send an image to the server using form data, everything seems fine until I try to add data from a crop plugin. Here is the code snippet: //create form data from form var formData = new FormData($('#my-form')[0]); //append the image formD ...

Vacant area on the right side of the page

There seems to be an issue with the website where there is an empty space to the right, causing a horizontal scroll bar to appear at the bottom. Despite my efforts, I cannot seem to identify the root cause of this problem. While one solution would be to si ...

Retrieving Mouse Coordinates using Ajax in PHP

I'm wondering if it's feasible to send an Ajax request with mouse coordinates using PHP. For instance, I am fetching a page with cUrl and would like to trigger a mouse movement event on that page. At this point, I haven't written any code ...

Optimizing the position of the datepicker dropdown in Boostrap 4

I am currently utilizing Bootstrap 4 (final) with the boostrap-datepicker-plugin 1.7.1. Since Bootstrap 4 no longer uses .input-group-addon elements for the calendar icon, but instead .input-group-prepend and .input-group-append, I made some modificatio ...

"Learn the steps to toggle a sub menu using an onclick event and how to hide it using another

I created a sidebar navigation that displays submenus on mouseover, but I want them to open on click and close when clicking on the same tab. Please take a look at my code on this CodePen link. Thank you. <nav class="navigation"> <ul class="mai ...

"Troubleshooting: Sending null values through Jquery ajax to an MVC controller

The issue: I am facing a challenge with saving events in a calendar through ajax by sending the content to my controller function. Despite my efforts, I constantly see null values being passed to my database. Upon inspecting the Network tools console log ...

Encountering an error of "Object Expected" when trying to implement the

I am trying to set up the suckerfish menu as demonstrated on this instructional website. I keep getting an "object expected" error from the sample JavaScript code: $(document).ready(function () { $("#nav-one li").hover( function () ...

How can I retrieve the selected items from a Listbox control?

Currently, I am working on an ASP.NET application using C#. One of the features in my project involves a Grid View with a Listbox control. The Listbox is initially set to be disabled by default. My goal is to enable and disable this control dynamically bas ...

What is the best way to split up the information and place it into separate text boxes?

I am currently working on a page that allows users to create and edit email structures. To facilitate editing, I added two columns to the page. One of the columns displays information from all the email structures along with two buttons - one for editing ...

I'm struggling to achieve the placement of my logo and navigation bar side by side

Check out the codes here body{ margin: 0; } .logo { text-indent: -999999px; background: url('logo3.png'); width: 216px; height: 219px; } .header{ width: 100%; height: auto; background-color: #eef3f5; padd ...

Error encountered in onclick handler due to unterminated string literal in PHP and jQuery

Trying to utilize PHP to send variables into the onclick of an element is resulting in an "Unterminated string literal" error due to long strings. Below is a snippet of my PHP code: $query = $conn->prepare("SELECT Name, Image, Description, Link, Price, ...

evolving the design of mui stepper

I am looking to customize the code below for my specific needs I want to change the icon from to this: I am unable to modify the style and also need to add an intermediate step I have included , '.Mui-active': { color: '#1C6FC9', }, ...

How can you utilize jQuery to iterate through nested JSON and retrieve a specific matching index?

In the scenario where I have a nested JSON object like this: var library = { "Gold Rush": { "slides": ["Slide 1 Text","Slide 2 Text","Slide 3 Text","Slide 4 Text"], "bgs":["<img src='1.jpg' />","","<img src='2.j ...

Using regular expressions to validate input in Javascript

Seeking assistance to validate an input text using the pattern <some_string>:<some_string> in JS/JQuery. For instance: A110:B120 AB12C:B123 I understand this might seem overly simplistic, but any guidance would be greatly appreciated. ...

Troubleshooting: Issues with MagicSuggest's dependent multiple dropdown functionality

Currently implementing MagicSuggest for a custom dropdown feature with two dropdowns: category and subcategory. The goal is to have the subcategories populate based on the selected category. However, after selecting a category and then a subcategory, if ...