Styling CSS for Grouped Rows in Tables

I need help with styling a table that contains variable data, grouped by columns (Month and Year).

My goal is to alternate row colors for each group of data. For example, all rows under Feb 2016 would have class=a, the next set of data would have class=b, and so on. It's like an odd/even pattern but applied to multiple rows based on their values.

https://i.sstatic.net/hwn37.png

In the image above, there are 3 datasets: Feb 2016, June 2016, Jan 2017. The first 4 rows would have class=a, rows 5 and 6 would have class=b, and the last row would go back to class=a.

Although I managed to do a simple alternating row color scheme, this task seems more complex.

Here is the dataset in a fiddle: https://jsfiddle.net/yo04vxoa/

Any guidance on how to achieve the desired result shown here: https://jsfiddle.net/yo04vxoa/3/ would be greatly appreciated!

I'm struggling to correctly assign classes to rows based on similar data in the month/year columns. Any assistance would be helpful.

Answer №1

If you're searching for a solution, this code snippet should provide what you need: https://jsfiddle.net/nx35pdwa/4/

$(data).find('requests').each(function() {
    var $p = $(this.previousElementSibling);
    if (this.previousElementSibling &&
        ($p.find('month').text() !== $(this).find('month').text() ||
         $p.find('year').text() !== $(this).find('year').text() )) {
      alt = !alt;
    }
    output += '<tr' + (alt ? ' class="alt" ' : '') + '>';
    output += '<td>' + $(this).find('month').text() + '</td>';
    output += '<td>' + $(this).find('year').text() + '</td>';
    output += '<td>' + $(this).find('title').text() + '</td>';
    output += '</tr>'
})

By comparing the current field with the previous one, you can determine when to add an alternate modifier class:

Answer №2

One way to achieve a similar result is by implementing the following code snippet:

let flip = false;
let flipType = 'even';
$('table tbody tr').each(function(index)
{    
   let current = $('table tbody tr').eq(index).find('td').eq(2).text();
   let next = $('table tbody tr').eq(index + 1).find('td').eq(2).text();
   if(next != ""){
    if(current == next){
      if(flip)
        $(this).addClass("odd");
      else
         $(this).addClass("even");
   }
   else {
      $(this).addClass(flipType);
      flipType = "even" ? "odd" : "even";
      flip = true;
    }
  }
  else 
  {
    flipType = "odd" ? "even" : "odd";  
    $(this).addClass(flipType);
    }
});

For an example, you can visit: https://jsfiddle.net/DinoMyte/yo04vxoa/6/

Answer №3

Take a look at https://jsfiddle.net/yo04vxoa/7/

This script dynamically assigns classes to table rows after the table has been created. A hidden column was introduced in the table to store the month and year information for each row, which is then used to create an array of elements. The script then iterates over this array, changing the color class based on the stored values.

Here's the new column added:

<th style="display:none;">ColourDate</th>

And here is the code snippet:

var myVals = [];
$(".dateColour").each(function(){
  myVals.push( { el: $(this), t: $(this).text()});
});

var lastVal = myVals[0].t;
var myClass = 'a';

$.each(myVals, function(i, e){
    if (e.t !== lastVal){
        lastVal = e.t;
        myClass = myClass == 'a'? 'b' : 'a';
    }
  e.el.parent().addClass(myClass);
});

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

How can I adjust the position of a circular progress bar using media queries?

My code involves creating a circular progress bar. However, I am facing an issue where the circles stack on top of each other when I resize the window, as shown in the output screenshot. I want to ensure that the position of the 3 circles remains fixed whe ...

How to stop empty numbers in angular.js

My goal is to ensure that an input with a required attribute always has some value, and if left empty, defaults to zero. <input ng-model='someModel' required> I have created the following directive: App.directive('input', fun ...

There seems to be a problem with the external JavaScript file not functioning

After dragging and dropping the .js file into my ASP.NET project, I am facing an issue where it remains unresponsive, even though the code works fine when used inline. This problem is occurring while using VS 2017. Here is a snippet of my code: <scrip ...

Set the state of a nested array object within SectionList data using the index

I'm currently working on populating a SectionList with data retrieved from a SQLite database. Here is where I begin: constructor(props) { super(props); this.state = { loading: true, sectionListData: [ { ...

Update the text content of an HTML element by fetching data from a database using AJAX and JQuery based on its

I recently started learning Jquery and came across an issue while working on a web development project. I am trying to dynamically convert an HTML element to a paragraph based on the ID from the URL which is fetched from the database. Here is the code sni ...

Ways to extract the directive's value specific to my scenario

I'm currently working on developing a directive for my Angular app, and I need to find a way to pass a value to my controller. Here's what I have so far: controllers.directive('checkBox', function() { return { restrict: &a ...

Trouble linking HTML, Javascript, and CSS - seeking help to get them working properly

Hey there! I'm currently trying to transfer my project from Codepen at here to repl.it (This project) which you can find at this link. Don't forget to click run after checking it out! The code is working perfectly fine on Brackets with the same ...

When using v-select to search for items, the selected items mysteriously vanish from

I recently worked on a project where I encountered a similar situation to the one showcased in this CodePen. Here is the link to the specific CodePen One issue I faced was that the selected items would disappear when performing an invalid search. After i ...

Reset ng-model when ng-show is not active in AngularJS

Hey there, I'm facing a little issue. I have an input field that sometimes needs to be displayed in a form and sometimes not. I'm worried that if someone enters data, hides it, and then hits send, the data will still be sent. That's why I w ...

How to center a span using Twitter Bootstrap

As a newcomer to Twitter Bootstrap, I'm wondering how I can center a span within a parent row. Currently, I am working with Twitter Bootstrap Version 2.3 instead of 3.1. In version 3.1, there is a center-block feature that I cannot utilize in 2.3. Th ...

When working with mongoose, express, node.js, and javascript, sometimes a

function getPassword(uname) { User.findOne({'username': uname},{'password': 1}, function(err, cb) { console.log("print 2"); return cb.password; }); console.log("print 1"); } I'm currently learning ...

Having trouble triggering a click event on Ant Design menu button using jest and enzyme

Troubleshooting the simulation of a click event on the Menu component using Antd v4.3.1 Component: import React from 'react' import PropTypes from 'prop-types' import { Menu } from 'antd' import { SMALL_ICONS, PATHS } fro ...

Using JQuery AJAX and an ASP.NET handler to upload files

After numerous attempts, I still can't seem to get this to work properly as I keep encountering errors while trying to upload a file. ASPX <asp:FileUpload ID="FileUpload1" runat="server" CssClass="file-upload-dialog" /> <asp:But ...

PHP is returning a null value as the last value, but JQuery is able to correctly select the last row from the

I'm currently facing a challenge in passing variables from HTML/PHP to jQuery for AJAX. Below is the code snippet: <?php $propertyid = $data['property_id']; $select5 = $con->prepare("SELECT favorite_properties_id, favorite_pro ...

Stop the browser from displaying a customized frameset within the document of an iframe

For some time now, I have been attempting to establish communication between two iframes that belong to the same domain but are embedded on a page from a different domain. The issue arises when the browser imposes a custom frameset layer over the content ...

Is there a way to display my array within my React component using JavaScript?

I am working with an element that looks like this: const DropdownElements = [ { key: 1, title: "City", placeholder: "Select City", apiUrl: "https://api.npoint.io/995de746afde6410e3bd", type: "city&qu ...

Combining various data types within a single field in BigQuery

Is it feasible to specify a table schema with a field that allows for multiple data types? For instance: BIGQUERY TABLE SCHEMA schema: [{ name: 'field1', type: 'string', }, { name: 'field2', type: &apo ...

AWS Lambda Error: Module not found - please check the file path '/var/task/index'

Node.js Alexa Task Problem Presently, I am working on creating a Node.js Alexa Skill using AWS Lambda. One of the functions I am struggling with involves fetching data from the OpenWeather API and storing it in a variable named weather. Below is the relev ...

The background image fails to display

Having some trouble with setting an image as the background using CSS. When I directly input the image URL, it shows up fine with this code: background: url('images/image1.jpg); However, I would prefer to use this CSS code instead: .masthead { m ...

Displaying information from a Node.js server on a React frontend

I have a question about building a simple REST API with Node.js and fetching mock data to render in React. Here is my progress so far: Node.js: const Joi = require("@hapi/joi"); const express = require("express"); const cors = require("cors"); const app ...