Printing json in html table - javascript

Here is my json APi -- >>> https://api.myjson.com/bins/p18mi
I have a table in which I have to print the Json data.
The problem is I want to print the Question data in major Question header and User_info array in thofUser column.
But its not working as expected. I am not able to arrange the table data properly so that all the user details must come User column and sub column. Same for question.
The output i am getting is this is image
$(function() {
var people = [];
$.getJSON('https://api.myjson.com/bins/p18mi', function(data) {
$.each(data.ct_info, function(i, f) {
var tblRow = " <tr>" + `<td id=${f.id}>` + `${f.id}` + "</td>" +
"<td>" + f.name + "</td>";
$(tblRow).appendTo("#userdata tbody");
var users = []
var question = []
f.Qid_info.forEach((x) => {
x.user_info.forEach((y) => {
//avoid duplicates
var foundUser = users.find((user) => {
return user.id === y.id
})
if (!foundUser) {
users.push(y)
}
})
})
f.Qid_info.forEach((x) => {
var foundQuestion = question.find((questions) => {
return questions.id === x.id
})
if (!foundQuestion) {
question.push(x)
}
})
$.each(question, function(i, question) {
var questionRow = `<td id=${question.id}>` + `${question.id}` +
"</td>" + "<td>" + question.isActive + "</td><td>" + question.iscomplex + "</td>" +
"<td>" + question.isbreakdown + "</td>"
$(questionRow).appendTo("#userdata tbody");
})
$.each(users, function(i, user) {
var userRow = `<td id=${user.id}>` + `${user.id}` +
"</td>" + "<td>" + user.name + "</td><td>" + user.data + "</td>" +
"<td>" + user.updatedAt + "</td>"
$(userRow).appendTo("#userdata tbody");
})
});
});
});
#user {
overflow-x: auto;
white-space: nowrap;
}
th,
td {
font-weight: normal;
padding: 5px;
text-align: center;
width: 120px;
vertical-align: top;
}
th {
background: #00B0F0;
}
tr+tr th,
tbody th {
background: #DAEEF3;
}
tr+tr,
tbody {
text-align: left
}
table,
th,
td {
border: solid 1px;
border-collapse: collapse;
table-layout: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='userdata'>
<tr>
<th colspan="2" id="ct">CT INFO</th>
<th colspan="4" id="que">Question</th>
<th colspan="4" id="user">User Info</th>
</tr>
<tr>
<th>CT ID</th>
<th>CT</th>
<th>Id</th>
<th>isActive</th>
<th>is Complex</th>
<th>is Breakdown</th>
<th>ID</th>
<th>NAME</th>
<th>Data</th>
<th>updatedAt</th>
</tr>
<tbody>
</tbody>
</table>

Start by using the template literal correctly and then realise you cannot append some unfinished row.
Also you need a thead, or the browser will insert an extra tbody
You need to add a colspanned cell for ct for each question and each user and add a colspanned cell for each question to the user.
It could be done with rowspan but that is up to you now.
Lastly your keys are "is complex" and "is breakdown"
$(function() {
var people = [];
var ctCells = [], questionCells = [], userCells = [];
var $tBody = $("#userdata tbody");
$.getJSON('https://api.myjson.com/bins/p18mi', function(data) {
$.each(data.ct_info, function(i, f) {
ctCells.push(`<td id=${f.id}>${f.id}</td><td>${f.name}</td>`);
var users = []
var question = []
f.Qid_info.forEach((x) => {
x.user_info.forEach((y) => {
//avoid duplicates
var foundUser = users.find((user) => {
return user.id === y.id
})
if (!foundUser) {
users.push(y)
}
})
})
f.Qid_info.forEach((x) => {
var foundQuestion = question.find((questions) => {
return questions.id === x.id
})
if (!foundQuestion) {
question.push(x)
}
})
$.each(question, function(i, question) {
ctCells.push(`<td colspan="2"> </td>`)
questionCells.push(`<td id=${question.id}>${question.id}</td><td>${question.isActive}</td><td>${question["is complex"]}</td><td>${question["is breakdown"]}</td>`);
})
$.each(users, function(i, user) {
ctCells.push(`<td colspan="2"> </td>`)
questionCells.push(`<td colspan="4"> </td>`)
userCells.push(`<td id=${user.id}>${user.id}</td><td>${user.name}</td><td>${user.data}</td><td>${user.updatedAt}</td>`);
})
});
$.each(userCells,function(i) {
$tBody.append(`<tr>${ctCells[i]}${questionCells[i]}${userCells[i]}</tr>`)
})
});
});
#user {
overflow-x: auto;
white-space: nowrap;
}
th,
td {
font-weight: normal;
padding: 5px;
text-align: center;
width: 120px;
vertical-align: top;
}
th {
background: #00B0F0;
}
tr+tr th,
tbody th {
background: #DAEEF3;
}
tr+tr,
tbody {
text-align: left
}
table,
th,
td {
border: solid 1px;
border-collapse: collapse;
table-layout: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='userdata'>
<thead>
<tr>
<th colspan="2" id="ct">CT INFO</th>
<th colspan="4" id="que">Question</th>
<th colspan="4" id="user">User Info</th>
</tr>
<tr>
<th>CT ID</th>
<th>CT</th>
<th>Id</th>
<th>isActive</th>
<th>is Complex</th>
<th>is Breakdown</th>
<th>ID</th>
<th>NAME</th>
<th>Data</th>
<th>updatedAt</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

A general idea is to decouple the logic from the printing.
In that case,
parse the json as an array (a matrix for that matter)
then print your array.
Advantages are amongst:
you can test your "extracting"
you can also chose to display differently as done below
To parse the json
every user is a row
and in front of some of them, prepend the question, and eventually the ct_info (or blanks otherwise)
To print the array
either print all tds, and apply css afterwards
You can use td:empty{border:0;}. See that SO link
Or brutally merge the empty tds in front of the row as inline colspan
$(function() {
var people = [];
function myJsonTable(data){
function pushFront(fields){
return function(x,i){
if(i==0) return (x.unshift(...fields),x);
return (x.unshift(...fields.map(_=>'')),x);
}
}
return data.ct_info.reduce((rows, ct_info,i)=>{
let questionUsers = ct_info.Qid_info.reduce((acc, question)=>{
let users = question.user_info.map(({id, name, data, updatedAt})=>{
return [id, name, data.join(','), updatedAt]
});
//for each user
//[user, user, user]
//consider its transpose
//[[...user]
// [...user]
// [...user]
// ]
// and prepend the question on first column
// you obviously have to spread everything, this is just for illustration purpose
// [[question, user]
// [[] , user]
// [[] , user]
let q = [question.id, question.isActive, question['is complexe'], question['is breakdown']]
return acc.concat(users.map(pushFront(q)));
},[]);
//do the same for each info
// [[info1, question, user]
// [[], [] , user]
// [[], question, user]
// [[], [] , user]
// [info2, question, user]
// [[], [] , user]
// ]
return rows.concat(questionUsers.map(pushFront([ct_info.id, ct_info.name])))
},[]);
}
$.getJSON('https://api.myjson.com/bins/p18mi', function(data) {
let table = myJsonTable(data);
let dom = table.map(row=>'<tr>'+row.map(cell=>`<td>${cell}</td>`).join('')+'</tr>');
$('table:eq(0) tbody').append(dom);
let dom1 = table.map(row=>{
let idx = row.findIndex(cell=>cell!='');
let tds = row.slice(idx).map(cell=>`<td>${cell}</td>`).join('')
let colspan = idx>0? `<td colspan="${idx}"></colspan>`:'';
return `<tr>${colspan}</td>${tds}</tr>`;
});
$('table:eq(1) tbody').append(dom1);
});
});
#user {
overflow-x: auto;
white-space: nowrap;
}
th,
td {
font-weight: normal;
padding: 5px;
text-align: center;
width: 120px;
vertical-align: top;
}
th {
background: #00B0F0;
}
tr+tr th,
tbody th {
background: #DAEEF3;
}
tr+tr,
tbody {
text-align: left
}
table,
th,
td {
border: solid 1px;
table-layout: fixed;
}
/* --------------------- */
table{
border-collapse: collapse;
/*empty-cells:hide; cannot use if border-collapse!=separate, setting separate with border-spacing:0 makes ugly borders*/
}
/*https://stackoverflow.com/questions/18758373/why-do-the-css-property-border-collapse-and-empty-cells-conflict*/
td:empty{
border:0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
css
<table id='userdata'>
<thead>
<tr>
<th colspan="2" id="ct">CT INFO</th>
<th colspan="4" id="que">Question</th>
<th colspan="4" id="user">User Info</th>
</tr>
<tr>
<th>CT ID</th>
<th>CT</th>
<th>Id</th>
<th>isActive</th>
<th>is Complex</th>
<th>is Breakdown</th>
<th>ID</th>
<th>NAME</th>
<th>Data</th>
<th>updatedAt</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<hr/>
inline colspan
<table id='userdata'>
<thead>
<tr>
<th colspan="2" id="ct">CT INFO</th>
<th colspan="4" id="que">Question</th>
<th colspan="4" id="user">User Info</th>
</tr>
<tr>
<th>CT ID</th>
<th>CT</th>
<th>Id</th>
<th>isActive</th>
<th>is Complex</th>
<th>is Breakdown</th>
<th>ID</th>
<th>NAME</th>
<th>Data</th>
<th>updatedAt</th>
</tr>
</thead>
<tbody>
</tbody>
</table>

Related

setting a value in the dropdowns in table based on imported values [javascript, jquery]

I have a table that is filled dynamically with a csv file. I created a table that inside itself has dropdowns in some columns.
What I want to do now is to check if a value exists in the cell where the dropdown is supposed to be, if so to check if it exists in the dropdownlist if yes then set this as selected in dropdown list otherwise selected is at default value and the cell gets red margine around.
Here is a jsFiddle with an example as how my code currently looks like:
https://jsfiddle.net/r236uy5k/
EDIT : I corrected my jsfiddle:
https://jsfiddle.net/kcau7jhd/
$(function(){
var firstDDM = ['aaa','bbb','ccc','ddd'];
var firstshortcut = ['a','b','c','d'];
var option = "",
select = "";
for(var i=0; i<firstDDM.length;i++){
option += '<option value="'+ firstshortcut[i] + '">' + firstDDM[i] + '</option>';
}
select = '<select class="firstDDM" type="firstDDM">' + option + '</select>';
$("tr").each(function() {
$(this).find("td:eq(3)").append(select);
});
});
$(function(){
var secondDDM = ['Default','AAA','BBB','B1','C'];
var secondshortcut = ['Default','a','b','b1','c'];
var option = "",
select = "";
for(var i=0; i<secondDDM.length;i++){
option += '<option value="'+ secondshortcut[i] + '">' + secondDDM[i] + '</option>';
}
select = '<select class="secondDDM" type="secondDDM">' + option + '</select>';
$("tr").each(function() {
$(this).find("td:eq(5)").append(select);
});
});
$("#addRow").click(function(){
$("#my_id").each(function(){
var tds='<tr>';
jQuery.each($('tr:last th', this), function(){
tds += '<th>' +'<input type="checkbox" name="record" tittle="Delete this row"></input>' + '</th>';
});
jQuery.each($('tr:last td', this), function(){
if($('select',this).length){
tds+= '<td>' + $(this).html() + '</td>';
}else{
tds+= '<td></td>';
}
});
tds+= '</tr>';
$('tbody',this).append(tds);
$('#my_id tbody tr:last').attr("contentEditable", true);
});
});
//for the columns that need to be imported with dropdowns create editable option - temporarlly
$(function() {
$("tr").each(function() {
$(this).find("td:eq(3), td:eq(4),td:eq(5)").attr("contentEditable", true);
});
});
//Find and remove selected table rows
$('#delete-row').click(function(){
var r = confirm('Are you sure you want to delete them all?');
$("tbody").find('input[name="record"]').each(function(){
if($(this).is(":checked")){
if(r == true){
$(this).parents("tr").remove();
}else{
return false;
}
}
});
});
table {
border-collapse: collapse;
border: 1px black solid;
font: 12px sans-serif;
width: 100%;
table-layout:auto;
}
td {
border: 1px black solid;
text-align: left;
padding: 2px;
}
thead:hover{
text-decoration: none !important;
}
thead tr:first-child{
color:white;
text-align: center;
background-color: #5bc0de;
padding: 10px;
}
tr:nth-child(even){
background-color: #f2f2f2
}
tr:hover{
background-color: #5bc0de;
}
button{
display: inline;
padding: 50px;
}
input button{
display: inline;
}
.dropbtn{
background-color: blue;
}
.table-responsive {
overflow-y: auto;
height: 800px;
}
.table-responsive table {
border-collapse: collapse;
width: 100%;
}
.table-responsive thead th{
position: sticky;
top: 0;
background-color: #5bc0de;
padding: 2px;
}
::-webkit-scrollbar {
width: 12px;
}
::-webkit-scrollbar-thumb {
background-color: darkgrey;
outline: 1px solid slategrey;
}
.myButtons{
display: inline;
padding: 20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Filtered CSV File</title>
</head>
<body>
<h1>
Filtered CSV FIle
</h1>
<br/>
<br/>
<div class="myButtons">
<input type="button" value="Add new row" class="btn btn-info" id="addRow">
<input type="button" value="Delete rows" id="delete-row" class="btn btn-info">
</div>
<br/>
<div class="table-responsive">
<table class="dataframe my_class" id="my_id">
<thead>
<tr style="text-align:right;">
<th> </th>
<th>col1</th>
<th>col2</th>
<th>col3</th>
<th>col4</th>
<th>col5</th>
<th>col6</th>
<th>col7</th>
<th>col8</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>row1</td>
<td>row1</td>
<td>row1</td>
<td></td>
<td>row1</td>
<td>B1</td>
<td>row1</td>
<td>row1</td>
</tr>
<tr>
<th>2</th>
<td>row2</td>
<td>row2</td>
<td>row2</td>
<td></td>
<td>row2</td>
<td>AAA</td>
<td>row2</td>
<td>row2</td>
</tr>
<tr>
<th>3</th>
<td>row3</td>
<td>row3</td>
<td>row3</td>
<td></td>
<td>row3</td>
<td>C</td>
<td>row3</td>
<td>row3</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
You can edit the select text you are entering. Following are the things which I think you want to achieve:
Identify if the dropdown has a certain value and preselect them if possible.
If the dropdown does not have correct value for pre selection then mark them as error field.
If the above mentioned points are incorrect please let me know i will make the relevant changes which are required.
I have added a condition check if (firstshortcut[i] == $(this).find("td:eq(3)")[0].innerHTML) you can replace it with any condition that you want.
Replace the following jquery snippets
$("tr").each(function () {
var option = "",
select = "",
classObject = '',
isSelected = false;
if($(this).find("td:eq(3)")[0]){
for (var i = 0; i < firstDDM.length; i++) {
if (firstshortcut[i] == $(this).find("td:eq(3)")[0].innerHTML) {
option += '<option selected="selected" value="' + firstshortcut[i] + '">' + firstDDM[i] + '</option>';
isSelected = true;
}
else
option += '<option value="' + firstshortcut[i] + '">' + firstDDM[i] + '</option>';
}
classObject = !isSelected ? 'errorDropDown' : '';
select = '<select class="firstDDM' + ' ' + classObject + '" type="firstDDM">' + option + '</select>'
$(this).find("td:eq(3)").append(select);
}
});
Add this class to the css file:
.errorDropDown {border: 1px solid red;}

Cannot read property 'childNodes' checkbox to get value from same row

Below code should get me the value of the column next to the checked box in the table, but, once the button is clicked, I am getting:
Cannot read property childNodes of null
Note: database from firebase which where the values from the table come from
Table image :
rootRefReAgents.on("child_added", snap => {
var AgentName = snap.child("Name").val();
$("#table_body_Test").append("<tr><td>" + AgentName + "</td><td><INPUT TYPE=\"Checkbox\"> </Input></td></tr>");
});
}
function ActionData(){
let agents = [];
let table = document.getElementById("table_body_Test");
let childNodes = Array.from(table.childNodes);
// let childNodes = table.childNodes;
for (let child of childNodes.values()) {
console.log(`child: ${child}`);
if (child.constructor.name !== "HTMLTableRowElement") {
continue;
}
let agent = child.childNodes.item(1).innerHTML;
console.log(`agent: ${agent}`);
let checkbox = child.childNodes.item(3).childNodes.item(1);
console.log(`checkbox: ${checkbox}`);
console.log(checkbox.checked);
if (checkbox.checked) {
agents.push(agent);
}
}
console.log(`agents: ${agents}`);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
<button id="submitBtn" onclick="ActionData()">Next</button>
ES6 brought new methods that simplify the code and its reading
const tableBody = document.querySelector('#testTable tbody' );
document.querySelector('#submitBtn').onclick=()=>
{
let agents = [];
console.clear();
for (let rowX of tableBody.rows )
{
let
agent = rowX.cells[0].textContent,
checkbox = rowX.cells[1].querySelector('input[type=checkbox]')
;
console.log( 'agent:', agent, 'checked:', checkbox.checked);
if (checkbox.checked) { agents.push(agent); }
}
console.log( 'agents (array):', agents.join(' / '));
}
/// bonus info :
/*
rootRefReAgents.on("child_added", snap=>{
let
newRow = tableBody.insertRow(-1);
newRow.insertCell(0).textContent = snap.child("Name").val();
newRow.insertCell(1).innerHTML = '<input type="Checkbox">';
});
*/
#testTable { margin: auto; border-collapse: collapse }
#testTable thead tr {
color: #D2002E;
background: #FFCC01;
height:32px;
font-weight: bold;
}
#testTable tr:nth-child(even) {background-color: lightgrey }
#testTable td { border:1px solid grey; padding: 0 20px; }
#testTable td:nth-child(2) { text-align: center }
<table id="testTable">
<thead>
<tr> <td>Agents</td> <td>Select</td> </tr>
</thead>
<tbody>
<tr> <td>AMC</td> <td> <input type="checkbox" > </td> </tr>
<tr> <td>Mygulfex</td> <td> <input type="checkbox" > </td> </tr>
<tr> <td>topStar</td> <td> <input type="checkbox" > </td> </tr>
<tr> <td>WMC</td> <td> <input type="checkbox" > </td> </tr>
</tbody>
</table>
<button id="submitBtn" >see Selects in console</button>

Using not(selector) on dynamically create element

The code basically edit a table cell.
I want to use the not() method so that everytime I click outside the temporary input created I replace it with a table cell. I guess the code run in a block and doesn't detect any input with an id of "replace" so how can I fix that ?
Also I want to store the element (th or td) that fire the first event(dblclick) so that I can use it to replace the input with the right type of cell but it seems to only stores the element that first triggers the event and I don't really understand why.
Full code here
$(function () {
$(document).on("dblclick", "th, td", function (event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
var $typeCell = $(event.currentTarget); // Store element which trigger the event
$("body").not("#replace").on("click", function () { // .not() method
cellText = $("#replace").val();
if ($typeCell.is("th")) {
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
}
else {
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
});
});
I have modified HTML and JavaScript to avoid any possible errors. The correct practice is to wrap all th's in a thead and all td's in tbody.
$(document).on("dblclick", "th, td", function(event) {
var cellText = $(this).text();
$(this).replaceWith("<input type='text' id='replace' value='" + cellText + "'>");
});
$("body").on("click", function() {
if (event.target.id != 'replace' && $('#replace').length != 0) {
var cellText = $("#replace").val();
if ($('#replace').parents().is('thead'))
$("#replace").replaceWith("<th scope='col'>" + cellText + "</th>");
else
$("#replace").replaceWith("<td>" + cellText + "</td>");
}
});
table {
border-collapse: collapse;
margin: 20px;
min-width: 100px;
}
table,
th,
td {
border: 1px solid grey;
padding: 4px;
}
th {
background: springgreen;
}
tr:nth-child(odd) {
background: rgba(0, 255, 127, 0.3);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<table>
<thead>
<tr>
<th scope="col">Uno</th>
<th scope="col">Dos</th>
<th scope="col">Tres</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data1</td>
<td>Data2</td>
<td>Data3</td>
</tr>
<tr>
<td>Data4</td>
<td>Data5</td>
<td>Data6</td>
</tr>
</tbody>
</table>
</div>

Toggling nested Table Columns - html, jQuery

I'm relatively new to jQuery but more seasoned using html and css.
I'm currently working on creating a new report that displays a nested table with quarterly results.Sample Quarterly Report
When a user clicks the img next to Q1 or Q2 table row - my expectation is for the Week (wk1 - wkn) columns to hide/show (toggle) as needed.
Additionally, when week columns are hidden, i would like the Quartely column(s) to collapse and dynamically show the sum of hidden weeks (wk1 - wkn).
Most of the code is borrowed from other posts but unfortunately, i was unable to find one that collapses and sums nested columns.
Thanks in advance for your help!
$(document).ready(function () {
var mImg = "http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png";
var pImg = "http://t3.gstatic.com/images?q=tbn:4TZreCjs_a1eDM:http://www.venice.coe.int/images/plus.png";
var sum1 = 0;
$('tr').find('.combat1').each(function () {
var combat1 = $(this).text();
if (!isNaN(combat1) && combat1.length !== 0) {
sum1 += parseFloat(combat1);
}
});
var sum2 = 0;
$('tr').find('.combat2').each(function () {
var combat2 = $(this).text();
if (!isNaN(combat2) && combat2.length !== 0) {
sum2 += parseFloat(combat2);
}
});
var sum3 = 0;
$('tr').find('.combat3').each(function () {
var combat3 = $(this).text();
if (!isNaN(combat3) && combat3.length !== 0) {
sum3 += parseFloat(combat3);
}
});
$('.total-combat1').html(sum1);
$('.total-combat2').html(sum2);
$('.total-combat3').html(sum3);
$('.header').click(function() {
//$('td:nth-child(2)').hide();
// if your table has header(th), use this
$('td:nth-child(2),th:nth-child(2)').toggle();
});
});
body {
background: #80dfff;
color: #d5d4d4;
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
margin: 0;
overflow-x: auto;
padding: 30px;
}
table {
background: white;
border-collapse: collapse;
border: 1px #393939 solid;
color: black;
margin: 1em 1em 1em 0;
}
thead {
border-collapse: collapse;
color: black;
}
th, td {
border: 1px #aaa solid;
padding: 0.2em;
}
<table>
<thead>
<tr><th colspan=8>2015</th></tr>
<tr><th colspan=4 class="header">Q1
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
<th colspan=3 class="header">Q2
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
<th></th>
</tr>
<tr>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
<th>WK4</th>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="combat1">8170</td>
<td class="combat1">6504</td>
<td class="combat1">6050</td>
<td class="combat1">6050</td>
<td class="combat1">7050</td>
<td class="combat1">7050</td>
<td class="combat1">7050</td>
<td class="total-combat1"></td>
</tr>
<tr>
<td class="combat2">8500</td>
<td class="combat2">10200</td>
<td class="combat2">7650</td>
<td class="combat2">7650</td>
<td class="combat2">8650</td>
<td class="combat2">8650</td>
<td class="combat2">8650</td>
<td class="total-combat2"></td>
</tr>
<tr>
<td class="combat3">9185</td>
<td class="combat3">5515</td>
<td class="combat3">6185</td>
<td class="combat3">7185</td>
<td class="combat3">9185</td>
<td class="combat3">9185</td>
<td class="combat3">9185</td>
<td class="total-combat3"></td>
</tr>
</tbody>
</table>
If you need to toggle the visibility of Q1 or Q2 you can change the header click event in order to obtain the effect produced in the following snippet.
The problem is to select all the cells of your interest and than toggle the visibility.
One way is to limit the cells selected using the jQuery :lt and :gt plus the css
$(function () {
var mImg = "http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png";
var pImg = "http://t3.gstatic.com/images?q=tbn:4TZreCjs_a1eDM:http://www.venice.coe.int/images/plus.png";
var sum1 = 0;
$('tr').find('.combat1').each(function () {
var combat1 = $(this).text();
if (!isNaN(combat1) && combat1.length !== 0) {
sum1 += parseFloat(combat1);
}
});
var sum2 = 0;
$('tr').find('.combat2').each(function () {
var combat2 = $(this).text();
if (!isNaN(combat2) && combat2.length !== 0) {
sum2 += parseFloat(combat2);
}
});
var sum3 = 0;
$('tr').find('.combat3').each(function () {
var combat3 = $(this).text();
if (!isNaN(combat3) && combat3.length !== 0) {
sum3 += parseFloat(combat3);
}
});
$('.total-combat1').html(sum1);
$('.total-combat2').html(sum2);
$('.total-combat3').html(sum3);
// The new header click event
$('.header').click(function(e) {
var isVisible = false;
var strSelector = '';
var everyTotIndex = 4;
if (this.innerText.trim() == 'Q1') {
everyTotIndex = 4;
strSelector = 'td:not([colspan="4"]):lt(4), th:not([colspan="4"]):lt(4)';
} else {
everyTotIndex = 3;
strSelector = 'td:not([colspan="3"]):lt(7):gt(3), th:not([colspan="3"]):lt(7):gt(3)';
}
$(this).parents('table').find('tr:eq(2), tbody > tr').find(strSelector).css('display', function(index, value) {
if (this.style.display == 'none') {
isVisible = true;
if ((index % everyTotIndex) == 0) {
$(this).parent().find('td[colspan="' + everyTotIndex + '"], th[colspan="' + everyTotIndex + '"]').remove();
}
return '';
}
if ((index % everyTotIndex) == 0) {
if (this.tagName.toLowerCase() == 'th') {
$('<th colspan="' + everyTotIndex + '" class="total">Total</th>').insertBefore($(this));
} else {
$('<td colspan="' + everyTotIndex + '" class="combat1 total">0</td>').insertBefore($(this));
var obj = $(this).parent().find('td[colspan="' + everyTotIndex + '"]');
obj.text(+obj.text() + parseInt(this.textContent));
}
} else {
if (this.tagName.toLowerCase() == 'td') {
var obj = $(this).parent().find('td[colspan="' + everyTotIndex + '"]');
obj.text(+obj.text() + parseInt(this.textContent));
}
}
return 'none';
});
if (isVisible) {
$(this).find('img').attr('src', "http://www.unesco.org/ulis/imag/minus.png");
} else {
$(this).find('img').attr('src', "http://www.unesco.org/ulis/imag/plus.png");
}
});
});
body {
background: #80dfff;
color: #d5d4d4;
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
margin: 0;
overflow-x: auto;
padding: 30px;
}
table {
background: white;
border-collapse: collapse;
border: 1px #393939 solid;
color: black;
margin: 1em 1em 1em 0;
}
thead {
border-collapse: collapse;
color: black;
}
th, td {
border: 1px #aaa solid;
padding: 0.2em;
}
<script src="http://code.jquery.com/jquery-1.11.3.js"></script>
<table>
<thead>
<tr><th colspan=8>2015</th></tr>
<tr><th colspan=4 class="header">Q1
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
<th colspan=3 class="header">Q2
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
<th></th>
</tr>
<tr>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
<th>WK4</th>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="combat1">8170</td>
<td class="combat1">6504</td>
<td class="combat1">6050</td>
<td class="combat1">6050</td>
<td class="combat1">7050</td>
<td class="combat1">7050</td>
<td class="combat1">7050</td>
<td class="total-combat1"></td>
</tr>
<tr>
<td class="combat2">8500</td>
<td class="combat2">10200</td>
<td class="combat2">7650</td>
<td class="combat2">7650</td>
<td class="combat2">8650</td>
<td class="combat2">8650</td>
<td class="combat2">8650</td>
<td class="total-combat2"></td>
</tr>
<tr>
<td class="combat3">9185</td>
<td class="combat3">5515</td>
<td class="combat3">6185</td>
<td class="combat3">7185</td>
<td class="combat3">9185</td>
<td class="combat3">9185</td>
<td class="combat3">9185</td>
<td class="total-combat3"></td>
</tr>
</tbody>
</table>
I tried to figure out what you was trying to do... Correct if me I wrong: you're trying to toggle the set of columns under, for e.g. Q1, when you click on the header column? If so, here the code. I modified your code, I added to nested tables under the main table to organize/ divide the two sets of information so I can select easily with jQuery which one I'm going to toggle.
$(document).ready(function() {
var mImg = "http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png";
var pImg = "http://t3.gstatic.com/images?q=tbn:4TZreCjs_a1eDM:http://www.venice.coe.int/images/plus.png";
var sum1 = 0;
$('tr').find('.combat1').each(function() {
var combat1 = $(this).text();
if (!isNaN(combat1) && combat1.length !== 0) {
sum1 += parseFloat(combat1);
}
});
var sum2 = 0;
$('tr').find('.combat2').each(function() {
var combat2 = $(this).text();
if (!isNaN(combat2) && combat2.length !== 0) {
sum2 += parseFloat(combat2);
}
});
var sum3 = 0;
$('tr').find('.combat3').each(function() {
var combat3 = $(this).text();
if (!isNaN(combat3) && combat3.length !== 0) {
sum3 += parseFloat(combat3);
}
});
$('.header-1').click(function() {
$("#table1").toggle();
});
$('.header-2').click(function() {
$("#table2").toggle();
});
});
body {
color: #d5d4d4;
font-family: Helvetica, Arial, sans-serif;
font-size: 12px;
margin: 0;
overflow-x: auto;
padding: 30px;
}
table {
background: white;
border-collapse: collapse;
border: 1px #393939 solid;
color: black;
margin: 0;
padding: 0;
}
thead {
border-collapse: collapse;
color: black;
}
th,
td,
tr {
border: 1px #aaa solid;
padding: 0;
}
td.combat {
padding: 0.2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th colspan=2>2015</th>
</tr>
<tr>
<th class="header-1">Q1
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
<th class="header-2">Q2
<img src="http://t1.gstatic.com/images?q=tbn:1PS9x2Ho4LHpaM:http://www.unesco.org/ulis/imag/minus.png" />
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<table id="table1">
<tr>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
<th>WK4</th>
</tr>
<tr>
<td class="combat combat1">8170</td>
<td class="combat combat1">6504</td>
<td class="combat combat1">6050</td>
<td class="combat combat1">6050</td>
</tr>
<tr>
<td class="combat combat1">8170</td>
<td class="combat combat1">6504</td>
<td class="combat combat1">6050</td>
<td class="combat combat1">6050</td>
</tr>
</table>
</td>
<td>
<table id="table2">
<tr>
<th>WK1</th>
<th>WK2</th>
<th>WK3</th>
</tr>
<tr>
<td class="combat combat2">7050</td>
<td class="combat combat2">7050</td>
<td class="combat combat2">7050</td>
</tr>
<tr>
<td class="combat combat2">7050</td>
<td class="combat combat2">7050</td>
<td class="combat combat2">7050</td>
</tr>
</table>
</td>
<td>
<table>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</td>
</tr>
</tbody>
</table>

Table and mouse rollover effect (hover)

I have this table:
<table border="1">
<tr>
<td></td>
<td>Banana</td>
<td>Orange</td>
<td>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td>1:1</td>
<td>1:2</td>
<td>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td>2:1</td>
<td>1:1</td>
<td>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td>1:3</td>
<td>2:1</td>
<td>1:1</td>
</tr>
and CSS:
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
What I want to do, is when I for example point my mouse on 1:3 table cell, it should highlight together with Banana and Plum cells.
Any easy way to do it?
Here's fiddle:
http://jsfiddle.net/CZEJT/
If you dont mind a bit of Javascript in there to ensure compatibility, take a look at this JSFiddle
HTML:
<table>
<tr>
<th></th><th>50kg</th><th>55kg</th><th>60kg</th><th>65kg</th><th>70kg</th>
</tr>
<tr>
<th>160cm</th><td>20</td><td>21</td><td>23</td><td>25</td><td>27</td>
</tr>
<tr>
<th>165cm</th><td>18</td><td>20</td><td>22</td><td>24</td><td>26</td>
</tr>
<tr>
<th>170cm</th><td>17</td><td>19</td><td>21</td><td>23</td><td>25</td>
</tr>
<tr>
<th>175cm</th><td>16</td><td>18</td><td>20</td><td>22</td><td>24</td>
</tr>
</table>
CSS:
table {
border-spacing: 0;
border-collapse: collapse;
overflow: hidden;
z-index: 1;
}
td, th, .ff-fix {
cursor: pointer;
padding: 10px;
position: relative;
}
td:hover::after,
.ff-fix:hover::after {
background-color: #ffa;
content: '\00a0';
height: 10000px;
left: 0;
position: absolute;
top: -5000px;
width: 100%;
z-index: -1;
}
tr:hover{
background-color: #ffa;
}
}
JS:
function firefoxFix() {
if ( /firefox/.test( window.navigator.userAgent.toLowerCase() ) ) {
var tds = document.getElementsByTagName( 'td' );
for( var index = 0; index < tds.length; index++ ) {
tds[index].innerHTML = '<div class="ff-fix">' + tds[index].innerHTML + '</div>';
};
var style = '<style>'
+ 'td { padding: 0 !important; }'
+ 'td:hover::before, td:hover::after { background-color: transparent !important; }'
+ '</style>';
document.head.insertAdjacentHTML( 'beforeEnd', style );
};
};
firefoxFix();
below is an example from one of my sites (css):
/*when hover over shape 5 dim shape 5*/
#shape5{
opacity:1.0;
filter:alpha(opacity=100);}
#shape5:hover{
opacity:0.4;
filter:alpha(opacity=40);}
/*When hoverover text5 dim shape 5!*/
#text5:hover + #shape5{opacity:0.4;
filter:alpha(opacity=40);}
Hope that helps!!
Oh Also view: How to affect other elements when a div is hovered
would you like something like this?
unfortunately it would be necessary some javascript
HTML
<table border="1">
<tr>
<td></td>
<td id='1'>Banana</td>
<td id='2'>Orange</td>
<td id='3'>Plum</td>
</tr>
<tr>
<td>Banana</td>
<td class='o1'>1:1</td>
<td class='o2'>1:2</td>
<td class='o3'>1:3</td>
</tr>
<tr>
<td>Orange</td>
<td class='o1'>2:1</td>
<td class='o2'>1:1</td>
<td class='o3'>1,5:1</td>
</tr>
<tr>
<td>Plum</td>
<td class='o1'>1:3</td>
<td class='o2'>2:1</td>
<td class='o3'>1:1</td>
</tr>
</table>
JAVASCRIPT
var cells1 = $('.o1');
cells1.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#1').css({background: '#ddd'})
})
cells1.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#1').css({background: 'none'})
})
var cells2 = $('.o2');
cells2.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#2').css({background: '#ddd'})
})
cells2.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#2').css({background: 'none'})
})
var cells3 = $('.o3');
cells3.on('mouseover', function(){
$($(this).parent().children()[0]).css({background: '#ddd'})
$('#3').css({background: '#ddd'})
})
cells3.on('mouseout', function(){
$($(this).parent().children()[0]).css({background: 'none'})
$('#3').css({background: 'none'})
})
CSS
td {
height:60px;
width:60px;
text-align:center;
}
td:hover{
background-color:red;
}
Try this:
Fiddle
Without changing your html structure or adding any third party library:
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var tds = document.getElementsByTagName('td');
for (var i = 0; i < tds.length; i++) {
var elem = document.getElementsByTagName('td')[i];
elem.addEventListener('mouseover', function () {
var text = this.innerHTML;
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
if (elem2.innerHTML == text) {
elem2.style.background = 'red';
}
}
}, false);
elem.addEventListener('mouseout', function () {
for (var j = 0; j < tds.length; j++) {
var elem2 = document.getElementsByTagName('td')[j];
var text = this.innerHTML;
if (elem2.innerHTML == text) {
elem2.style.background = 'none';
}
}
}, false);
}
}, false);
</script>
I apologise that my answer is only in pseudo code, however I would approach this problem by using javascript (most possibly Jquery). I hope this makes sense...
<table id="tbl"> - so I would give the table an ID
<td onHover="changeHeaderColummns(this)"></td> - then on each of the columns have a jsMethod that fires.
<script>
changeHeaderColumsn(col)
{
var colIndex = col.Index; //get the current column index
var row = GetHeaderRow(); // get the header row
highLightColumn(row, colIndex); //change the colour of the cell
//with the same index in the header
row = getCurrentRow(col.RowIndex); //now get the current row
highlightColumn(row, 0); //change the colour of the cell
//with the index of 0
}
getHeaderRow()
{
return getRow(0);
}
getRow(rowIndex)
{
var table = document.getElementByID("tbl);
return table.rows[rowIndex];
}
highlightColumn(row, colIndex)
{
row[colIndex].style.backgroundcolor = "red";
}
for highlight columns you must use js like this jsfiddler. It's work with jQuery ;)
With code
Using jquery
fiddle: http://jsfiddle.net/itsmikem/CZEJT/12/
Option 1: highlights the cell and just the named fruit cells
$("td").on({
"mouseenter":function(){
$(this).closest("tr").find("td:first-child").css("background","#f99");
var col = $(this).index();
$(this).closest("table").find("tr:first-child").find(String("td:nth-child(" + (col + 1) + ")")).css("background","#f99");
$(this).css("background","#f00");
},
"mouseleave":function(){
$(this).closest("table").find("td,tr").css("background","none");
}
});
Option 2: highlights entire rows and columns that intersect the hovered cell
$("td").on({
"mouseenter": function () {
$(this).closest("tr").css("background", "#f99");
var col = $(this).index();
var myTable = $(this).closest("table");
var rows = $(myTable).find("tr");
$(rows).each(function (ind, elem) {
var sel = String("td:nth-child(" + (col + 1) + ")");
$(this).find(sel).css("background", "#f99");
});
$(this).css("background", "#f00");
},
"mouseleave": function () {
$(this).closest("table").find("td,tr").css("background", "none");
}
});

Categories