Change rows based on order number in database

I am creating a site for ordering pizza for my education project. With the stackoverflow community, I have already achieved a lot - so thanks! But now I am stuck and cannot find any working solution for my problem.

Question

How to change alternating row color (white / gray / white / gray ...) depending on ordernumber in the database (mysqli)? ordernumber can be on more than one line, so I cannot just change the color in a row after line.

I tried with jquery, but this only works if the order numbers are always on the list (even / odd) ... if the order is canceled, then it no longer works (see image with missing order number 7)

Here is the code in jquery:

 $(document).ready(function() { var check = 0; for(var i =0; i<= $("tr").length;i++){ $("tr").each(function(){ if(parseInt($(this).find("#bestnr").text())==check){ if(check%2 == 0){ $(this).css("background-color","white"); }else{ $(this).css("background-color","#DCDCDC"); } } }); check +=1; } }); 

Any ideas? Thank you for your help!

+5
source share
2 answers

Since you are working with jQuery, something like this should do the trick - explanations in the code comments.

 $(document).ready(function() { // define the initial "previous order id" as 0 assuming // there will never be an order with id 0 var previousOrderId = 0; var previousBgColour = '#dcdcdc'; var thisBgColour; // loop the table rows $("tr").each(function() { // determine "this" row id (assuming bestnr is short for bestelnummer) // and that the text in that table cell *is* the order number // I've changed this to a class as an id HAS to be unique // you'll need to update your code to accommodate var thisOrderId = parseInt($(this).find(".bestnr").text()); // define the background colour based on whether the order id has changed // if it has change it if(thisOrderId != previousOrderId) { thisBgColour = previousBgColour == '#dcdcdc' ? '#ffffff' : '#dcdcdc'; previousBgColour = thisBgColour; } else { thisBgColour = previousBgColour; } $(this).css({'background-color' : thisBgColour}); //update the previousOrderId to this id previousOrderId = thisOrderId; }); }); 

Basically, you keep the previous order ID and compare it with the current order ID - if the order ID has not changed, it will use the previous background color if it displays it on an alternative color.

+5
source

If it's just alternating colors, you can use CSS directly and not worry about anything else:

 tr:nth-child(odd) { background-color:white; } tr:nth-child(even) { background-color:#DCDCDC; } 

If it somehow depends on the logic of the backend, we can look at adding a class to jQuery and adding colors to this class using CSS

0
source

All Articles