I'm creating for my education-project a pizza-ordering website. With the help of the stackoverflow-community I've achieved already a lot - so thank you! But now I'm stuck and can't find any working solution to my problem.
Question
How can I change the row color alternating (white / grey / white / grey ...) depending on the ordernumber in the database(mysqli)? The ordernumber can be in more than one row, so I can not simple change the color row by row.
I've tried with jquery, but this works only if the ordering numbers remain always in the list (even/odd) ... if an order is cancelled, then it doesn't works anymore (see image with missing ordernumber 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? Thanks for your help!
Since you're working with JQuery, something like this ought to do the trick - explanations in 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;
});
});
You're basically storing the previous order id and comparing it to the current order id - if the order id hasn't changed it'll use the previous background colour, if it has it'll flipflop it to the alternate colour.
If it is 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 this is somehow dependent on logic from the backend, we can look at adding a class in jQuery and adding colors to this class via CSS
Related
I have a code to calculate some qty in the table which loaded dynamically. And also i have added code to change the class of a if the qty is less than zero. But in my case, that changing the color at one time i.e., in first row not in rest of the rows.
$(document).ready(function() {
$("#itemtable").on("change", "input", function() {
var row = $(this).closest("tr");
var received = parseFloat(row.find("td:eq(5)").text()); // get received qty
var accepted = parseFloat($(row).find("td:eq(6) input[type='text']").val());
if (received < accepted){
alert("Accepted qty greater than received qty, Please check!");
} else {
var rejected = received - accepted;
row.find("td:eq(7) input[type='text']").val(isNaN(rejected) ? "" : rejected);
}
if (rejected > 0){
alert("change class");
$('#rejec').removeClass('tb1').addClass('tb2');
}
});
});
in first row not in rest of the rows
The selector to find the reject text $("#reject") needs to include the row, ie:
$("#rejec", row).removeClass('tb1').addClass('tb2');
or
row.find("#rejec").removeClass('tb1').addClass('tb2');
In general, IDs should be unique - if #rejec is on each row, it will only change the first one (as you've found). Ideally, use classes and filter to the event's row.
as above mentioned , changed this piece of code to get the required result
if (rejected > 0){
row.find("td:eq(7) input[type='text']").removeClass('tb1').addClass('tb2');
}
I wrote following code to add a custom column to my table. but i want to add a unique id to each cell in those columns. the format should be a(column no)(cell no>)
ex :- for the column no 4 :- a41, a42, a43, ........
So please can anyone tell me how to do that. Thank You!
$(document).ready(function ()
{
var myform = $('#myform'),
iter = 4;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
var colName = $("#txtText").val();
if (colName!="")
{
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
}
});
iter += 1;
});
});
You seem to have code that's modifying the contents of the table (adding cells), which argues fairly strongly against adding an id to every cell, or at least one based on its row/column position, as you have to change them when you add cells to the table.
But if you really want to do that, after your modifications, run a nested loop and assign the ids using the indexes passed into each, overwriting any previous id they may have had:
myform.find("tr").each(function(row) {
$(this).find("td").each(function(col) {
this.id = "a" + row + col;
});
});
(Note that this assumes no nested tables.)
try this
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
you just have to define and iterate the column_no and cell_no variable
When all other cells are numbered consistently (for example using a data-attribute with value rXcX), you could use something like:
function addColumn(){
$('table tr').each(
function(i, row) {
var nwcell = $('<td>'), previdx;
$(row).append(nwcell);
previdx = nwcell.prev('td').attr('data-cellindex');
nwcell.attr('data-cellindex',
previdx.substr(0,previdx.indexOf('c')+1)
+ (+previdx.substr(-previdx.indexOf('c'))+1));
});
}
Worked out in this jsFiddle
I have a div with 4 css columns and I'd like to select the 3rd and 4th column to make the text slightly darker because I don't have a good contrast between the text and the background-image. Is this possible? I can accept any css or js solution.
Here's the demo.
--EDIT--
It seems that it's not possible to find a selector for pseudo blocks (if I may say) however I still need to figure out a way of creating responsive blocks (like columns) that will split the text equally (in width) whenever the browser is resized.
As far as I know you won't be able to apply styles to the columns.
What you can try however is to use a gradient as a background to make columns 3 and 4 another color.
#columns {
background: -webkit-linear-gradient(left, rgba(0,0,0,0) 50%, blue 50%);
/*... appropriate css for other browser engines*/
}
updated jsFiddle
updated with all browser support gradient
-- EDIT --
Since the intention was actually to change the text color and not the background for the third and fourth column some additional thoughts.
For now it doesn't seem possible to apply styles to single columns inside a container. One possible workaround to change the text color in specific columns is to put every word inside a span. Then to use JavaScript to iterate over the words and determine where a new column starts. Assigning the first element in the third column a new class would make it possible to style this and the following siblings with a different text color.
Because the container is part of a responsive layout and could change in size, the script would have to be re-run on the resize event to account for changing column widths.
The purpose of the code example is to outline how to implement such a solution and should be improved for use in an actual application (e.g. the spans are being re-created every time styleCols is run, lots of console output...).
JavaScript
function styleCols() {
// get #columns
var columns = document.getElementById('columns');
// split the text into words
var words = columns.innerText.split(' ');
// remove the text from #columns
columns.innerText = '';
// readd the text to #columns with one span per word
var spans = []
for (var i=0;i<words.length;i++) {
var span = document.createElement('span');
span.innerText = words[i] + ' ';
spans.push(span);
columns.appendChild(span);
}
// offset of the previous word
var prev = null;
// offset of the column
var colStart = null;
// number of the column
var colCount = 0;
// first element with a specific offset
var firsts = [];
// loop through the spans
for (var i=0;i<spans.length;i++) {
var first = false;
var oL = spans[i].offsetLeft;
console.info(spans[i].innerText, oL);
// test if this is the first span with this offset
if (firsts[oL] === undefined) {
console.info('-- first');
// add span to firsts
firsts[oL] = spans[i];
first = true;
}
// if the offset is smaller or equal to the previous offset this
// is a new line
// if the offset is also greater than the column offset we are in
// (the second row of) a new column
if ((prev === null || oL <= prev) && (colStart === null || oL > colStart)) {
console.info('-- col++', colCount + 1);
// update the column offset
colStart = oL;
// raise the column count
colCount++;
}
// if we have reached the third column
if (colCount == 3) {
// add our new class to the first span with the column offset
// (this is the first span in the current column
firsts[oL].classList.add('first-in-col3');
return;
}
// update prev to reflect the current offset
prev = oL;
}
}
styleCols();
addEventListener('resize', styleCols, false);
CSS
.first-in-col3, .first-in-col3~span {
color: red;
}
jsFiddle
For now i dont think you can do it, here https://bugzilla.mozilla.org/show_bug.cgi?id=371323 is an open bug/request for a feature, you can vote for it. Till then you can consider using tables.
P.S.
Give Up and Use Tables just for the sake of humor :)
The only solution i could think would be a background with your desired color for middle column, customize it for size and position so it goes behind your middle columns and make background-clip:text. Unfortunately it is not supported very well.
You can find more explenations here.
For example I selected (checked) 2 rows from second page than go to first page and select 3 rows. I want get information from 5 selected rows when I stay at first page.
$('tr.row_selected') - not working
Thanks.
Upd.
I created handler somthing like this:
$('#example').find('tr td.sel-checkbox').live("click", function () {
/*code here*/
});
But right now when click event is hadle the row from table is hidding. I think it may be sorting or grouping operation of DataTables. Any idea what I must do with this?
When a checkbox gets selected, store the row information you want in a global object as a Key-Value pair
I don't remember specifically how i did it before but the syntax was something like
$('input[type=checkbox]').click(function()
{
var row = $(this).parent(); //this or something like it, you want the TR element, it's just a matter of how far up you need to go
var columns = row.children(); //these are the td elements
var id = columns[0].val(); //since these are TDs, you may need to go down another element to get to the actual value
if (!this.checked) //becomes checked (not sure may be the other way around, don't remember when this event will get fired)
{
var val1 = columns[1].val();
var val2 = columns[2].val();
myCheckValues[id] =[val1,val2]; //Add the data to your global object which should be declared on document ready
}
else delete myCheckValues[id];
});
When you submit, get the selected rows from your object:
for (var i = 0; i < myCheckValues.length; i++)
...
Sorry, haven't done JS in a long time so code as is might not work but you get the idea.
$('#example').find('tr td.sel-checkbox').live("click", function () {
var data = oTable.fnGetData(this);
// get key and data value from data object
var isSelected = $(this).hasClass('row_selected');
if(isSelected) {
myCheckValues[key] = value;
checkedCount++;
} else {
delete myCheckValues[key];
checkedCount--;
}
});
.....
On submit
if(checkedCount > 0) {
for(var ArrVal in myCheckValues) {
var values = myCheckValues[ArrVal]; // manipulate with checked rows values data
}
}
The below code works properly, but it is hard coded. I would like to be able to create an array of field sets, hide those fields, then each time I click on the "#createEventForm-eventInformation-addElement" button it displays the next one. The problem with the below code is that it is hard coded and thus would break easily and be much larger than using loops. Can someone help me make this better.
$("#fieldset-group1").hide();
$("#fieldset-group2").hide();
$("#fieldset-group3").hide();
$("#fieldset-group4").hide();
$("#fieldset-group5").hide();
$("#fieldset-group6").hide();
$("#fieldset-group7").hide();
$("#fieldset-group8").hide();
$("#fieldset-group9").hide();
$("#createEventForm-eventInformation-addElement").click(
function() {
ajaxAddEventInformation();
if($("#fieldset-group1").is(":hidden"))
{
$("#fieldset-group1").show();
}
else
{
$("#fieldset-group2").show();
}
}
);
You should use the ^= notation of the jquery selectors which means starting with ..
// this will hide all of your fieldset groups
$('[id^="fieldset-group"]').hide();
Then
$("#createEventForm-eventInformation-addElement").click(
function() {
ajaxAddEventInformation();
// find the visible one (current)
var current = $('[id^="fieldset-group"]:visible');
// find its index
var index = $('[id^="fieldset-group"]').index( current );
// hide the current one
current.hide();
// show the next one
$('[id^="fieldset-group"]').eq(index+1).show();
}
);
A quick idea.
Add a class to each fieldset lets say "hiddenfields". Declare a global variable to keep track of which field is shown.
$(".hiddenfields").hide();//hide all
var num = 0;//none shown
$("#createEventForm-eventInformation-addElement").click(
function() {
ajaxAddEventInformation();
num++;
$("#fieldset-group" + num).show();
}
);
Here is one simple solution.
var index = 0;
var fieldsets = [
$("#fieldset-group1").show(),
$("#fieldset-group2"),
$("#fieldset-group3"),
$("#fieldset-group4"),
$("#fieldset-group5"),
$("#fieldset-group6"),
$("#fieldset-group7"),
$("#fieldset-group8"),
$("#fieldset-group9")
];
$("#createEventForm-eventInformation-addElement").click(function() {
ajaxAddEventInformation();
fieldsets[index++].hide();
if (index < fieldsets.length) {
fieldsets[index].show();
}
else {
index = 0;
fieldsets[index].show();
}
});
Add a class 'fieldset' to all fieldsets, then:
$("#createEventForm-eventInformation-addElement").click(
function() {
ajaxAddEventInformation();
$('.fieldset').is(':visible')
.next().show().end()
.hide();
}
);
This will show the first hidden fieldset element whose ID attribute starts with "fieldset-group"...
$("fieldset[id^='fieldset-group']:hidden:first").show();
How about to add (or only use) a class for that fields?
$(".fieldset").hide(); // hides every element with class fieldset
$("#createEventForm-eventInformation-addElement").click( function() {
ajaxAddEventInformation();
// I assume that all fieldset elements are in one container #parentdiv
// gets the first of all remaining hidden fieldsets and shows it
$('#parentdiv').find('.fieldsset:hidden:first').show();
});