I'm making a table which have alternate row colors, for example the first row is red, the second is green, the third is red and so on.
Written this code so far and got stuck, don't know what to put in if statement.
var color = "red";
var outputString = "<table border=1 width=50%>";
outputString = outputString + "<tr><td>a</td><td>a^2</td><td>a^3</td></tr>";
for (var i = 1; i <= 5; i++ ) {
if (i%2 == 0) {
} else {
}
outputString += "<tr class=" + color + ">" + "<td>" + i + "</td>" + "<td>" + i * i + "</td>" + "<td>" + i * i * i + "</td>" + "</tr>";
}
outputString += "</table>";
document.write(outputString);
Here is the pure css version,
table tr:nth-child(odd) td{
}
table tr:nth-child(even) td{
}
And here is the jQuery solution for the same,
$(function(){
$("table tr:even").addClass("evenClassName");
$("table tr:odd").addClass("oddClassName");
});
Here is the pure JavaScript solution,
function altrows(firstcolor,secondcolor)
{
var tableElements = document.getElementsByTagName("table") ;
for(var j = 0; j < tableElements.length; j++)
{
var table = tableElements[j] ;
var rows = table.getElementsByTagName("tr") ;
for(var i = 0; i <= rows.length; i++)
{
if(i%2==0){
rows[i].style.backgroundColor = firstcolor ;
}
else{
rows[i].style.backgroundColor = secondcolor ;
}
}
}
}
Use this(JQUERY WAY):-
$(document).ready(function()
{
$("table#tblid tr:even").css("background-color", "color code");
$("table#tblid tr:odd").css("background-color", "color code");
});
Here is the JavaScript way of doing it:-
var tblrows = document.getElementsByTagName('tr');
for(i=0;i<tblrows.length;i++){
if(i%2==0) tblrows[i].style.backgroundColor = '#f22000';
else tblrows[i].style.backgroundColor = '#a02141';
}
JS FIDDLE
use this, it will apply for all tables too
var tr = document.getElementsByTagName('tr');
for(i=0;i<tr.length;i++){
if(i%2==0) tr[i].style.backgroundColor = 'red';
}
DEMO
if you want to highlight the trs that have at least a td element inside use this :
var tr = document.getElementsByTagName('tr');
for(i=0;i<tr.length;i++){
if(i%2==0 && tr[i].getElementsByTagName('td').length) tr[i].style.backgroundColor = 'red';
}
Here is an alternative pure JavaScript + CSS solution.
// get all even rows
var evenRows = document.querySelectorAll('tr:nth-child(even)');
// get all odd rows
var oddRows = document.querySelectorAll('tr:nth-child(odd)');
// set even rows background color
evenRows.forEach((evenRow) => { evenRow.style.backgroundColor = 'myEvenRowColor'; });
// set odd rows background color
oddRows.forEach((oddRow) => { oddRow.style.backgroundColor = 'myOddRowColor'; });
This takes advantage of JavaScript's querySelectorAll and forEach functions and CSS selectors.
The above code can also be written in two lines:
document.querySelectorAll('tr:nth-child(even)').forEach((evenRow) => { evenRow.style.backgroundColor = 'myEvenRowColor'; });
document.querySelectorAll('tr:nth-child(odd)').forEach((oddRow) => { oddRow.style.backgroundColor = 'myOddRowColor'; });
Using just your code as a basis you'll want to do this in the if statement:
var color_even = "red";
var color_odd = "green";
var outputString = "<table border=1 width=50%>";
outputString = outputString + "<tr><td>a</td><td>a^2</td><td>a^3</td></tr>";
for (var i = 1; i <= 5; i++ ) {
if (i%2 == 0) {
color_used = color_even;
} else {
color_used = color_odd;
}
outputString += "<tr class=\"" + color_used + "\">" + "<td>" + i + "</td>" + "<td>" + i * i + "</td>" + "<td>" + i * i * i + "</td>" + "</tr>";
}
outputString += "</table>";
document.write(outputString);
Related
I have tried everything i know and can't get an alterate tablerow class to work , without having all the rows duplicated or having a bunch of dummy rows inserted
Here is what i have
<script>
fetch("https://www63.myfantasyleague.com/2021/export?TYPE=league&L=43570&JSON=1").then(
res => {
res.json().then(
data => {
console.log(data.league.franchises.franchise);
if (data.league.franchises.franchise.length > 0) {
var temp = "";
temp += "<table id='league_emails'>";
temp += "<tbody>";
temp += "<tr><th>Franchise</th><th>Owner Name</th><th>Email</th></tr>";
data.league.franchises.franchise.forEach((itemData) => {
for (var i = 0; i < data.league.franchises.franchise.length; i++) {
if (i % 2)
temp += '<tr class="eventablerow">';
else
temp += '<tr class="oddtablerow">';
}
temp += "<td>" + itemData.name + "</td>";
temp += "<td>" + itemData.owner_name + "</td>";
temp += "<td>" + itemData.email + "</td>";
});
temp += "</tbody>";
temp += "</table>";
document.getElementsByClassName('commish_league_safe')[0].innerHTML = temp;
}
}
)
}
)
</script>
<div class="commish_league_safe"></div>
The issue lays here and i have tried a dozen things and wrapped it different ways
for (var i = 0; i < data.league.franchises.franchise.length; i++) {
if (i % 2)
temp += '<tr class="eventablerow">';
else
temp += '<tr class="oddtablerow">';
}
<script>
fetch(https://www63.myfantasyleague.com/2021/export?TYPE=league&L=43570&JSON=1).then(
res => {
res.json().then(
data => {
console.log(data.league.franchises.franchise);
if (data.league.franchises.franchise.length > 0) {
var temp = "";
temp += "<table id='league_emails'>";
temp += "<tbody>";
temp += "<tr><th>Franchise</th><th>Owner Name</th><th>Email</th></tr>";
data.league.franchises.franchise.forEach((itemData,i) => {
/* for (var i = 0; i < data.league.franchises.franchise.length; i++) { */
if (i % 2)
temp += '<tr class="eventablerow">';
else
temp += '<tr class="oddtablerow">';
/* } */
temp += "<td>" + itemData.name + "</td>";
temp += "<td>" + itemData.owner_name + "</td>";
temp += "<td>" + itemData.email + "</td>";
temp += "</tr>";
});
temp += "</tbody>";
temp += "</table>";
document.getElementsByClassName('commish_league_safe')[0].innerHTML = temp;
}
}
)
}
)
</script>
<div class="commish_league_safe"></div>
Just before ending the loop close the tr tag.
temp += "" + itemData.email + ""; after this line just add closing tag to append that to temp variable.
I found this nice canvas pie on Github, but it's giving me some problem.
I'm not very good in JS, so I'm here asking for help.
https://github.com/jamesalvarez/draggable-piechart
In the example shown here, you can see a UI to manipulate the graphic.
https://codepen.io/Waterbear83/pen/vYOrbva?editors=0010
I don't understand how to display that UI even if I'm using the same js.
https://codepen.io/Waterbear83/pen/yLNqVBZ?editors=0010
Is there someone so nice to help?
Thanks!
function onPieChartChange(piechart) {
var table = document.getElementById("proportions-table");
var percentages = piechart.getAllSliceSizePercentages();
var labelsRow = "<tr>";
var propsRow = "<tr>";
for (var i = 0; i < proportions.length; i += 1) {
labelsRow += "<th>" + proportions[i].format.label + "</th>";
var v = "<var>" + percentages[i].toFixed(0) + "%</var>";
var plus =
'<div id="plu-' +
dimensions[i] +
'" class="adjust-button" data-i="' +
i +
'" data-d="-1">+</div>';
var minus =
'<div id="min-' +
dimensions[i] +
'" class="adjust-button" data-i="' +
i +
'" data-d="1">−</div>';
propsRow += "<td>" + v + plus + minus + "</td>";
}
labelsRow += "</tr>";
propsRow += "</tr>";
table.innerHTML = labelsRow + propsRow;
var adjust = document.getElementsByClassName("adjust-button");
function adjustClick(e) {
var i = this.getAttribute("data-i");
var d = this.getAttribute("data-d");
piechart.moveAngle(i, d * 0.1);
}
for (i = 0; i < adjust.length; i++) {
adjust[i].addEventListener("click", adjustClick);
}
}
[...] even if I'm using the same js
Not quite the same :) It misses this in your setup onchange: onPieChartChange
var newPie = new DraggablePiechart({
canvas: document.getElementById("piechart"),
data: data,
onchange: onPieChartChange
});
And then, after, in the onPieChartChange() there is also the dimensions (it's the same array but sorted randomly with the function knuthfisheryates2(), like you don't have this function in your code, it throws an error ReferenceError: dimensions is not defined because it does not exist) term to change in data in the function onPieChartChange(piechart). The same goes with proportions. But you can keep this one rather to replace it, it's handy to place common parameter like collapsed: false and to do operations on others like label: d.format.label.charAt(0).toUpperCase() + d.format.label.slice(1)
var proportions = data.map(function(d,i) { return {
label: d.format.label,
proportion: d.proportion,
collapsed: false,
format: {
color: d.format.color,
label: d.format.label.charAt(0).toUpperCase() + d.format.label.slice(1) // capitalise first letter
}
}});
function onPieChartChange(piechart) {
var table = document.getElementById("proportions-table");
var percentages = piechart.getAllSliceSizePercentages();
var labelsRow = "<tr>";
var propsRow = "<tr>";
for (var i = 0; i < proportions.length; i += 1) { // <------------------ HERE but keep --------
labelsRow += "<th>" + proportions[i].format.label + "</th>"; // <--- HERE but keep --------
var v = "<var>" + percentages[i].toFixed(0) + "%</var>";
var plus = '<div id="plu-' +
data[i] + // <----------------- HERE ------------------
'" class="adjust-button" data-i="' +
i +
'" data-d="-1">+</div>';
var minus =
'<div id="min-' +
data[i] + // <-------------- AND HERE -----------------
'" class="adjust-button" data-i="' +
i +
'" data-d="1">−</div>';
propsRow += "<td>" + v + plus + minus + "</td>";
}
labelsRow += "</tr>";
propsRow += "</tr>";
table.innerHTML = labelsRow + propsRow;
var adjust = document.getElementsByClassName("adjust-button");
function adjustClick(e) {
var i = this.getAttribute("data-i");
var d = this.getAttribute("data-d");
piechart.moveAngle(i, d * 0.1);
}
for (i = 0; i < adjust.length; i++) {
adjust[i].addEventListener("click", adjustClick);
}
}
Note: Couldn't make it works with the angles, I looked all his examples, he never uses it, he always uses proportions: proportions. So I just changed that in addition in your code.
The code is to large to be posted in a snippet here, here a codepen:
You can change the data from line 744 (see picture)
https://codepen.io/jghjghjhg/pen/rNVrwbd
I am trying to create a data table with my dataset and I want to reinitialize the same table for the new data. But it's getting appended to the same table rather than re-initialising it. This is my code
function showTab(name,data){
trheader = "";
trvalues = "";
trcontent = "";
trfoot = "";
table_id = "";
trheader += "<thead>";
for (i = 0; i < data[0].length; i++){
trheader += "<th>" + data[0][i]+ "</th>";
}
trheader += "</thead>";
if(data[1].length > 0){
for (i = 0; i < data[1].length; i++){
trvalues += "<tbody>"
trvalues += "<tr>"
trvalues += "<td class='center'>" + (i + 1) + "</td>";
trvalues += "<td class='center'>" + data[1][i][0] + "</td>";
for (j = 0; j < 4; j++ ){
trvalues += "<td class='center'>" + data[1][i][1][j].toLocaleString() + "</td>";
}
for(j = 4; j < 7; j++){
var patt = /^-/;
var color = data[1][i][1][j].toString();
if (color.match(patt)){
trvalues += "<td class='center redCell'>" + data[1][i][1][j].toFixed(2) + '%'+ "</td>";
}
else if(color == '0'){
trvalues += "<td></td>"
}
else{
trvalues += "<td class='center greenCell'>" + data[1][i][1][j].toFixed(2) + '%' + "</td>";
}
}
trvalues += "</tr>"
trvalues += "</tbody>"
}
}
if (data[2].length > 0)
{
trfoot += "<tfoot>"
trfoot += "<tr>"
trfoot += "<td></td>"
trfoot += "<td>Total</td>"
for (i = 0; i < 4; i++){
trfoot += "<td class='center'>" + data[2][i].toLocaleString() + "</td>";
}
for( i = 4; i < 7; i ++){
var patt = /^-/;
var color = data[2][i].toString();
if (color.match(patt)){
trfoot += "<td class='center redCell'>" + data[2][i].toFixed(2) + '%'+ "</td>";
}
else if(color == '0'){
trfoot += "<td></td>"
}
else{
trfoot += "<td class='center greenCell'>" + data[2][i].toFixed(2) + '%' + "</td>";
}
}
trfoot += "</tr>"
trfoot += "</tfoot>"
}
trcontent = trheader + trvalues + trfoot;
table = "#"+name;
$(table).html(trcontent);
$(table).DataTable({
"scrollY": "400px",
"scrollCollapse": true,
"paging": false,
"searching": false,
"destroy": true
});
// new addition code
var seen = {};
$('table tr').each(function() {
var txt = $(this).text();
if (seen[txt])
$(this).remove();
else
seen[txt] = true;
});
If I use $(table).html it will only load the last value that is trfooter. I have tried setting bDestroy for the table but nothing helps. Please help. Thanks.
This is my table skeleton
<table border = "1px"cellpadding="0" cellspacing="1" width="100%" id= <%= table&.table_name %> style="background: none repeat scroll 0% 0%;font-size:12px;">
</table>
You can destroy and re-declare your datatable to load the latest content
// First Declaration
var table = $('#myTable').DataTable();
$('#submit').on( 'click', function () {
$.getJSON( 'newTable', null, function ( json ) {
// Destroy
table.destroy();
$('#myTable').empty(); // empty in case the columns change
// ReDraw
table = $('#myTable').DataTable( {
columns: json.columns,
data: json.rows
} );
} );
} );
For more reference : https://datatables.net/reference/api/destroy()
I have the following code which works perfectly, but can I make the drop menu dynamic using quantityAllowed as the maximum the drop menu goes to. at the moment I have added 10 options for every print, but what i would prefer is the drop menus only have the correct quantity in. I think the loop I need would go where the options begin using the value of the loop, but when i have tried, i just get an error, so I know I have done something wrong.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
$("#tbNames tr:last").after("<tr>" +
"<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>" +
"<td class='printpoints'>" + calcTable[index].printPrice + "</td>" +
"<td>" + calcTable[index].quantityAllowed + "</td>" +
"<td><select " + myclass + "><option value=0>0</option><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select></td><td></td> </tr>");
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
You can separate out your HTML generation code from the jQuery DOM assignment. This makes it a little easier to read and manipulate. When you come to your select/option area, drop it into a for... loop to generate the appropriate number of options.
function arrayData() {
var index;
var text = "<ul>";
var htmlTable = '';
var calcTable = [];
calcTable = [
{ printName:"Name1", printPrice:8000000, quantityAllowed:6},
{ printName:"Name2", printPrice:12000000, quantityAllowed:5},
{ printName:"Name3", printPrice:20000000, quantityAllowed:4},
{ printName:"Name4", printPrice:2000000, quantityAllowed:3},
];//end of array
for (index = 0; index < calcTable.length; index++) {
var myclass = 'class="printwant"';
var output = '';
output += "<tr>";
output += "<td style='padding:0px 0px 0px 36px;'>" + calcTable[index].printName + "</td>";
output += "<td class='printpoints'>" + calcTable[index].printPrice + "</td>";
output += "<td>" + calcTable[index].quantityAllowed + "</td>";
output += "<td><select " + myclass + ">";
for( var i=0, x=calcTable[index].quantityAllowed; i<x; i++ ){
output += '<option value="' + i + '">' + i + '</option>';
}
output += "</select></td><td></td> </tr>";
$("#tbNames tr:last").after(output);
}//end of loop
$("#tbNames tr:last").after("<tr>" + "<td colspan = '5' height=40 > </tr>");
}
arrayData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbNames">
<tr></tr>
<tr></tr>
</table>
I am trying to create dynamic table in js.
var tableBody = document.createElement('TBODY');
table.appendChild(tableBody);
for (var i = 0; i < results.rows.length; i++)
{
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for(var j = 0; j < 7; j++)
{
var td = document.createElement('TD');
td.width = '75';
td.appendChild(document.createTextNode(results.rows.item(i).medicine_name));
tr.appendChild(td);
td.appendChild(document.createTextNode(results.rows.item(i).tm_1));
tr.appendChild(td);
td.appendChild(document.createTextNode(results.rows.item(i).tm_2));
tr.appendChild(td);
td.appendChild(document.createTextNode(results.rows.item(i).tm_3));
tr.appendChild(td);
td.appendChild(document.createTextNode(results.rows.item(i).dosage));
tr.appendChild(td);
td.appendChild(document.createTextNode(results.rows.item(i).diagnosis));
tr.appendChild(td);
td.appendChild(document.createTextNode(results.rows.item(i).instructions));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
When I execute this code, 7 rows will be created with all the items together. I want to insert each of the data in seperate columns. How can I do it? I want medicine_name to be in one column. tm_1 to be in another and so on.
**The rows will be decided based on results.rows.length value and the number of columns is 7
Totally you have 7 columns and 7 rows.So in first text node td.appendChild(document.createTextNode(results.rows.item((i*7) + 0).medicine_name)); And in second text node use
td.appendChild(document.createTextNode(results.rows.item((i*7) + 1).tm_1)); and so on...
for (var i = 0; i < results.length; i++) {
var html = "";
html += "<tr>";
html += "<td>" + results[i].MedicineName + "</td>";
html += "<td>" + results[i].tm_1+ "</td>";
html += "<td>" + results[i].tm_2+ "</td>";
html += "<td>" + results[i].dosage+ "</td>";
html += "<td>" + results[i].diagnosis+ "</td>";
html += "<td>" + results[i].instructions+ "</td>";
html += "</tr>";
$('#myTableDiv').append(html);
}
<script>
$(document).ready(function () {
var results = getResults();
createTable(results);
});
function createTable(results) {
for (var i = 0; i < results.length; i++) {
var html = "";
html += "<tr>";
html += "<td>" + results[i].MedicineName + "</td>";
html += "<td>" + results[i].tm_1 + "</td>";
html += "<td>" + results[i].tm_2 + "</td>";
html += "<td>" + results[i].dosage + "</td>";
html += "<td>" + results[i].diagnosis + "</td>";
html += "<td>" + results[i].instructions + "</td>";
html += "</tr>";
$('#myTableDiv').append(html);
}
}
function getResults() {
var Results = new Array(0);
for (var j = 0; j < 4; j++) {
var data = new medicine;
data.MedicineName = "Medicine" + j;
data.tm_1 = "tm1" + j;
data.tm_2 = "tm2" + j;
data.dosage = "tm3" + j;
data.diagnosis = "tm4" + j;
data.instructions = "tm5" + j;
Results.push(data);
}
return Results;
};
function medicine() {
var MedicineName = new String();
var tm_1 = new String();
var tm_2 = new String();
var dosage = new String();
var diagnosis = new String();
var instructions = new String();
}
</script>