Hiding all rows after a row click with a certain class [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I have a table with rows with different classes. What I want is that if a breakrow is clicked then all the data rows beneath it are either shown if they are hidden or hidden if they are shown. Here is an example of the table:
I found a stackoverflow thread with exactly what i needed but when i try to implement it it doesn't work. Any help would be awesome
Here is my HTML page. My table is dynamically generated.
$(document).ready(function() {
$("#gobutton").click(function() {
var userText = $("#inputText").val();
var data = processRawData(userText);
data = getAllData(data);
data = data.sort()
// extract all unique years
var years = [];
years = extractUniqueYears(years, data);
// extract all unique semesters
var semsetersUn = [];
semsetersUn = extractUniqueSemesters(semsetersUn, data);
var cumulative = [];
cumulative = calculateCumulativeGPA(cumulative, data);
var yearly = [];
yearly = calculateYearlyGPA(yearly, data, years);
var semesterly = [];
semseterly = calculateSemesterlyGPA(semesterly, data, semsetersUn);
console.log(cumulative);
console.log(yearly);
console.log(semseterly);
tableString = '<table>' + createTableHeaders();
for (var i = 0; i < yearly.length; i++) {
tableString = tableString + createYearRow(yearly[i][0], yearly[i][1], yearly[i][2], yearly[i][3]);
for (var j = 0; j < semseterly.length; j++) {
if (semseterly[j][4] == yearly[i][4]) {
tableString = tableString + createSemesterRow(semseterly[j][0], semseterly[j][1], semseterly[j][2], semseterly[j][3]);
}
}
}
console.log(tableString);
tableString = tableString + '</tbody></table>';
$("#gradesTable").append(tableString);
});
$('.first-level').click(function() {
$(this).nextUntil('.first-level').toggle("slow");
});
});
function getAllData(data) {
data = getTwelvePoint(data);
data = isIncluded(data);
data = addAcademicYear(data);
data = addSemester(data);
data = calculateCredits(data)
data = convertUnits(data);
return data;
}
function processRawData(rawData) {
var format = /[A-Z]+ +(.*)+\n+(.*)+\n+(.*)+\n+(.*)+\n+(.*)+\n+(.*)+/gm;
var courses = [];
while ((row = format.exec(rawData)) !== null) {
var entry = row[0].split('\n');
courses.push(entry);
}
return courses;
}
function getTwelvePoint(courses) {
for (var i = 0; i < courses.length; i++) {
// get the Twelve Point grade from the letter grade
var grade = courses[i][3];
if (grade == 'A+') {
courses[i].push(12);
} else if (grade == 'A') {
courses[i].push(11);
} else if (grade == 'A-') {
courses[i].push(10);
} else if (grade == 'B+') {
courses[i].push(9);
} else if (grade == 'B') {
courses[i].push(8);
} else if (grade == 'B-') {
courses[i].push(7);
} else if (grade == 'C+') {
courses[i].push(6);
} else if (grade == 'C') {
courses[i].push(5);
} else if (grade == 'C-') {
courses[i].push(4);
} else if (grade == 'D+') {
courses[i].push(3);
} else if (grade == 'D') {
courses[i].push(2);
} else if (grade == 'D-') {
courses[i].push(1);
} else {
courses[i].push(0);
}
}
return courses;
}
function isIncluded(courses) {
for (var i = 0; i < courses.length; i++) {
if ((courses[i][5] == 'In Progress') || (courses[i][3] == 'NC') || (courses[i][3] == 'COM') || (courses[i][5] == 'Transferred')) {
courses[i].push(false);
} else {
courses[i].push(true);
}
}
return courses;
}
function addAcademicYear(courses) {
for (var i = 0; i < courses.length; i++) {
if (courses[i][2].substring(5, 9) == 'Fall') {
courses[i].push(parseInt(courses[i][2].substring(0, 4)));
} else {
courses[i].push(parseInt(courses[i][2].substring(0, 4)) - 1);
}
}
return courses;
}
function addSemester(courses) {
for (var i = 0; i < courses.length; i++) {
var semsester = courses[i][2].split(' ');
courses[i].push(semsester[1]);
}
return courses;
}
function extractUniqueYears(years, courses) {
for (var i = 0; i < courses.length; i++) {
if (courses[i][2].substring(5, 9) == 'Fall') {
years.push(parseInt(courses[i][2].substring(0, 4)));
} else {
years.push(parseInt(courses[i][2].substring(0, 4)) - 1);
}
}
years = Array.from(new Set(years));
return years;
}
function extractUniqueSemesters(semesters, courses) {
for (var i = 0; i < courses.length; i++) {
semesters.push(courses[i][2]);
}
semesters = Array.from(new Set(semesters));
semseters = semesters.sort();
return semesters;
}
function calculateCredits(courses) {
for (var i = 0; i < courses.length; i++) {
courses[i].push(courses[i][4] * courses[i][6]);
}
return courses;
}
function convertUnits(courses) {
for (var i = 0; i < courses.length; i++) {
courses[i][4] = parseFloat(courses[i][4]);
}
return courses;
}
function calculateCumulativeGPA(cumulative, courses) {
//calculate final gpa
totalCredits = 0;
totalUnits = 0.0;
for (var l = 0; l < courses.length; l++) {
if (courses[l][7] == true) {
totalUnits = totalUnits + parseInt(courses[l][4]);
totalCredits = totalCredits + courses[l][10];
}
}
cumulative = ['Cumulative', totalUnits.toString(), totalCredits.toString(), ((totalCredits / totalUnits).toFixed(2)).toString()];
return cumulative;
}
function calculateYearlyGPA(yearly, courses, years) {
var finalData = [];
//calculate yearly gpa
var totalCredits = 0;
var totalUnits = 0.0;
for (var j = 0; j < years.length; j++) {
totalCredits = 0;
totalUnits = 0;
for (var k = 0; k < courses.length; k++) {
if ((courses[k][8] == years[j]) && courses[k][7] == true) {
totalUnits = totalUnits + parseInt(courses[k][4]);
totalCredits = totalCredits + courses[k][10];
}
}
finalData[j] = [years[j].toString() + '-' + (years[j] + 1).toString(), totalUnits.toString(), totalCredits.toString(), ((totalCredits / totalUnits).toFixed(2)).toString()];
}
for (var i = 0; i < finalData.length; i++) {
finalData[i].push(parseInt(finalData[i][0]));
}
yearly = finalData;
return yearly;
}
function calculateSemesterlyGPA(semesterly, courses, semesters) {
var finalData = [];
//calculate yearly gpa
var totalCredits = 0;
var totalUnits = 0.0;
for (var j = 0; j < semseters.length; j++) {
totalCredits = 0;
totalUnits = 0;
for (var k = 0; k < courses.length; k++) {
if ((courses[k][2] == semesters[j]) && courses[k][7] == true) {
totalUnits = totalUnits + parseInt(courses[k][4]);
totalCredits = totalCredits + courses[k][10];
}
}
finalData[j] = [semesters[j], totalUnits.toString(), totalCredits.toString(), ((totalCredits / totalUnits).toFixed(2)).toString()];
}
finalData = academicYearID(finalData);
semesterly = finalData.sort();
return semesterly;
}
function academicYearID(data) {
for (var i = 0; i < data.length; i++) {
if (data[i][0].substring(5, 9) == 'Fall') {
data[i].push(parseInt(data[i][0].substring(0, 4)));
} else {
data[i].push(parseInt(data[i][0].substring(0, 4)) - 1);
}
}
return data;
}
function createTableHeaders() {
return '<thead><tr class="tableheader"><th>Time Period</th><th>Units Taken</th><th>Credits Earned</th><th>GPA</th></tr></thead><tbody>'
}
function createYearRow(TimePeriod, Units, Credits, grade) {
return '<tr class="breakrow"><td>' + TimePeriod.toString() + '</td><td>' + Units.toString() + '</td><td>' + Credits.toString() + '</td><td>' + grade.toString() + '</td></tr>';
}
function createSemesterRow(TimePeriod, Units, Credits, grade) {
return '<tr class="datarow"><td>' + TimePeriod.toString() + '</td><td>' + Units.toString() + '</td><td>' + Credits.toString() + '</td><td>' + grade.toString() + '</td></tr>';
}
table {
border-collapse: collapse;
width: 100%;
}
th,
td {
padding: 8px;
text-align: center;
border-bottom: 1px solid #ddd;
}
tr:hover {
background-color: #f5f5f5;
}
.datarow {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="Header">
<h1>Learning Query</h1>
</div>
<div class="container">
<textarea type="text" class="form-control" rows="11" id="inputText" placeholder="Paste Here"></textarea>
<button type="button" id="gobutton">Go</button>
<table id='gradesTable'>
<thead>
<tr class="tableheader">
<th>Time Period</th>
<th>Units Taken</th>
<th>Credits Earned</th>
<th>GPA</th>
</tr>
</thead>
<tbody>
<tr class="breakrow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="breakrow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="breakrow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="breakrow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div>

In your case, the rows which are equivalent to the .first-level rows in the SO thread you linked are of the class .breakrow. You may also want to toggle a class such as "hide" rather than "slow", since you're toggling whether they're hidden. Thus
$('.first-level').click(function() {
$(this).nextUntil('.first-level').toggle("slow");
});
should be rewritten as
$('.breakrow').click(function() {
$(this).nextUntil('.breakrow').toggle("hide");
});
This will toggle the class of "hide" on the correct rows. Then in your CSS you could implement the .hide class like
.datarow.hide {
display: none;
}
Just a note that you also currently have
.datarow {
display: none;
}
in your CSS, and you may want to remove that so that they are only hidden when they have a class of .hide. You can initialize them with the class of .hide on them if you want them hidden when the table loads.
Hope that helps!
PS - also note that the snippet of HTML you posted is missing a couple closing tags, </tbody> and </table :)

It seems that you are just missing the jQuery script tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).ready(function(){
$("#gobutton").click(function() {
var userText = $("#inputText").val();
var data = processRawData(userText);
data = getAllData(data);
data = data.sort()
// extract all unique years
var years = [];
years = extractUniqueYears(years,data);
// extract all unique semesters
var semsetersUn = [];
semsetersUn = extractUniqueSemesters(semsetersUn,data);
var cumulative = [];
cumulative = calculateCumulativeGPA(cumulative,data);
var yearly = [];
yearly = calculateYearlyGPA(yearly,data,years);
var semesterly = [];
semseterly = calculateSemesterlyGPA(semesterly,data,semsetersUn);
console.log(cumulative);
console.log(yearly);
console.log(semseterly);
tableString = '<table>' + createTableHeaders();
for(var i = 0; i<yearly.length; i++){
tableString = tableString + createYearRow(yearly[i][0],yearly[i][1],yearly[i][2],yearly[i][3]);
for(var j = 0; j<semseterly.length; j++){
if(semseterly[j][4] == yearly[i][4]){
tableString = tableString + createSemesterRow(semseterly[j][0],semseterly[j][1],semseterly[j][2],semseterly[j][3]);
}
}
}
console.log(tableString);
tableString = tableString + '</tbody></table>';
$("#gradesTable").append(tableString);
});
$('.first-level').click(function() {
$(this).nextUntil('.first-level').toggle("slow");
});
});
function getAllData(data){
data = getTwelvePoint(data);
data = isIncluded(data);
data = addAcademicYear(data);
data = addSemester(data);
data = calculateCredits(data)
data = convertUnits(data);
return data;
}
function processRawData(rawData){
var format = /[A-Z]+ +(.*)+\n+(.*)+\n+(.*)+\n+(.*)+\n+(.*)+\n+(.*)+/gm;
var courses = [];
while((row = format.exec(rawData)) !== null){
var entry = row[0].split('\n');
courses.push(entry);
}
return courses;
}
function getTwelvePoint(courses){
for (var i=0;i<courses.length;i++){
// get the Twelve Point grade from the letter grade
var grade = courses[i][3];
if(grade == 'A+'){
courses[i].push(12);
}
else if(grade == 'A'){
courses[i].push(11);
}
else if(grade == 'A-'){
courses[i].push(10);
}
else if(grade == 'B+'){
courses[i].push(9);
}
else if(grade == 'B'){
courses[i].push(8);
}
else if(grade == 'B-'){
courses[i].push(7);
}
else if(grade == 'C+'){
courses[i].push(6);
}
else if(grade == 'C'){
courses[i].push(5);
}
else if(grade == 'C-'){
courses[i].push(4);
}
else if(grade == 'D+'){
courses[i].push(3);
}
else if(grade == 'D'){
courses[i].push(2);
}
else if(grade == 'D-'){
courses[i].push(1);
}
else{
courses[i].push(0);
}
}
return courses;
}
function isIncluded(courses){
for (var i=0;i<courses.length;i++){
if((courses[i][5] == 'In Progress') || (courses[i][3] == 'NC') || (courses[i][3] == 'COM') || (courses[i][5] == 'Transferred')){
courses[i].push(false);
}
else{
courses[i].push(true);
}
}
return courses;
}
function addAcademicYear(courses){
for (var i=0;i<courses.length;i++){
if(courses[i][2].substring(5,9) == 'Fall'){
courses[i].push(parseInt(courses[i][2].substring(0,4)));
}
else{
courses[i].push(parseInt(courses[i][2].substring(0,4)) - 1);
}
}
return courses;
}
function addSemester(courses){
for (var i=0;i<courses.length;i++){
var semsester = courses[i][2].split(' ');
courses[i].push(semsester[1]);
}
return courses;
}
function extractUniqueYears(years,courses){
for (var i=0;i<courses.length;i++){
if(courses[i][2].substring(5,9) == 'Fall'){
years.push(parseInt(courses[i][2].substring(0,4)));
}
else{
years.push(parseInt(courses[i][2].substring(0,4)) - 1);
}
}
years = Array.from(new Set(years));
return years;
}
function extractUniqueSemesters(semesters,courses){
for (var i=0;i<courses.length;i++){
semesters.push(courses[i][2]);
}
semesters = Array.from(new Set(semesters));
semseters = semesters.sort();
return semesters;
}
function calculateCredits(courses){
for (var i=0;i<courses.length;i++){
courses[i].push(courses[i][4]*courses[i][6]);
}
return courses;
}
function convertUnits(courses){
for (var i=0;i<courses.length;i++){
courses[i][4] = parseFloat(courses[i][4]);
}
return courses;
}
function calculateCumulativeGPA(cumulative,courses){
//calculate final gpa
totalCredits = 0;
totalUnits = 0.0;
for (var l = 0; l<courses.length; l++){
if(courses[l][7] == true){
totalUnits = totalUnits + parseInt(courses[l][4]);
totalCredits = totalCredits + courses[l][10];
}
}
cumulative=['Cumulative',totalUnits.toString(),totalCredits.toString(),((totalCredits/totalUnits).toFixed(2)).toString()];
return cumulative;
}
function calculateYearlyGPA(yearly,courses,years){
var finalData = [];
//calculate yearly gpa
var totalCredits = 0;
var totalUnits = 0.0;
for (var j = 0; j<years.length; j++){
totalCredits = 0;
totalUnits = 0;
for(var k = 0; k<courses.length; k++){
if((courses[k][8] == years[j]) && courses[k][7] == true){
totalUnits = totalUnits + parseInt(courses[k][4]);
totalCredits = totalCredits + courses[k][10];
}
}
finalData[j]=[years[j].toString() + '-' + (years[j]+1).toString(),totalUnits.toString(),totalCredits.toString(),((totalCredits/totalUnits).toFixed(2)).toString()];
}
for(var i = 0; i<finalData.length; i++){
finalData[i].push(parseInt(finalData[i][0]));
}
yearly = finalData;
return yearly;
}
function calculateSemesterlyGPA(semesterly,courses,semesters){
var finalData = [];
//calculate yearly gpa
var totalCredits = 0;
var totalUnits = 0.0;
for (var j = 0; j<semseters.length; j++){
totalCredits = 0;
totalUnits = 0;
for(var k = 0; k<courses.length; k++){
if((courses[k][2] == semesters[j]) && courses[k][7] == true){
totalUnits = totalUnits + parseInt(courses[k][4]);
totalCredits = totalCredits + courses[k][10];
}
}
finalData[j]=[semesters[j],totalUnits.toString(),totalCredits.toString(),((totalCredits/totalUnits).toFixed(2)).toString()];
}
finalData = academicYearID(finalData);
semesterly = finalData.sort();
return semesterly;
}
function academicYearID(data){
for (var i = 0;i<data.length;i++){
if (data[i][0].substring(5,9) == 'Fall'){
data[i].push(parseInt(data[i][0].substring(0,4)));
}
else{
data[i].push(parseInt(data[i][0].substring(0,4))-1);
}
}
return data;
}
function createTableHeaders(){
return '<thead><tr class="tableheader"><th>Time Period</th><th>Units Taken</th><th>Credits Earned</th><th>GPA</th></tr></thead><tbody>'
}
function createYearRow(TimePeriod,Units,Credits,grade){
return '<tr class="breakrow"><td>' + TimePeriod.toString() + '</td><td>' + Units.toString() + '</td><td>' + Credits.toString() + '</td><td>' + grade.toString() + '</td></tr>';
}
function createSemesterRow(TimePeriod,Units,Credits,grade){
return '<tr class="datarow"><td>' + TimePeriod.toString() + '</td><td>' + Units.toString() + '</td><td>' + Credits.toString() + '</td><td>' + grade.toString() + '</td></tr>';
}
table {
border-collapse: collapse;
width: 100%;
}
th, td {
padding: 8px;
text-align: center;
border-bottom: 1px solid #ddd;
}
tr:hover {background-color:#f5f5f5;}
.datarow {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr class="tableheader">
<th>Time Period</th>
<th>Units Taken</th>
<th>Credits Earned</th>
<th>GPA</th>
</tr>
</thead>
<tbody>
<tr class="breakrow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="breakrow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="breakrow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="breakrow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr class="datarow">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<button id="gobutton">
Go
</button>

Related

javascript table contents into array result weird

I am trying to read table contents into array using javsscript , but the results are weird
All content is split character wise, even complete cell contents.
What could be wrong?
function BTN_() {
var t = document.getElementById("TBL");
var G = document.getElementById("result");
var FF = [];
var R = t.rows.length; //TTL_rows
//FF += R ;
for (M = 0; M <= R - 1; M++) {
var TTL_row_cells = t.rows[M].cells.length;
for (C = 0; C <= TTL_row_cells - 1; C++) {
FF += t.rows[M].cells[C].innerHTML;
}
}
LN = FF.length;
document.write(LN + "<br/>");
for (V = 0; V <= LN - 1; V++) {
document.write(FF[V] + ",");
}
}
#TBL,
td {
border: 1px solid #cdcdcd
}
button {
font-size: 36px
}
<body style="font-size:36px">
<table id="TBL">
<tr>
<th>Heading1</th>
<th>Heading2</th>
</tr>
<tr>
<td>R1</td>
<td>R1</td>
</tr>
<tr>
<td>R2</td>
<td>R2</td>
</tr>
</table>
<div id="result"></div>
<hr />
<button onclick="BTN_()">Button</button>
</body>
result
24
H,e,a,d,i,n,g,1,H,e,a,d,i,n,g,2,R,1,R,1,R,2,R,2,
Instead of pushing data in array, you concat as a string. Here the cleanup you can do. Once push, then can join.
function BTN_() {
var t = document.getElementById("TBL");
var G = document.getElementById("result");
var FF = [];
var R = t.rows.length; //TTL_rows
//FF += R ;
for (M = 0; M <= R - 1; M++) {
var TTL_row_cells = t.rows[M].cells.length;
for (C = 0; C <= TTL_row_cells - 1; C++) {
FF.push(t.rows[M].cells[C].innerText)
}
}
LN = FF.length;
document.write(LN + "<br/>");
document.write(FF.join("<br/>"));
}
<table id="TBL">
<tr>
<th>Heading1</th>
<th>Heading2</th>
</tr>
<tr>
<td>R1</td>
<td>R1</td>
</tr>
<tr>
<td>R2</td>
<td>R2</td>
</tr>
</table>
<div id="result"></div>
<hr />
<button onclick="BTN_()">Button</button>

How to show data from a database in my table from my website?

I have a database that I want to access to display my product data, in this case the ItemCode and ItemName.
the connections are all correct and the functional, my problems is the loop and show the data in the table that I have in the html file.
let ctrl = {
showDados: function(r) {
/*dados[3].ItemCode;*/
let dados = JSON.parse(r.responseText);
let cod = dados.ItemCode;
let name = dados.ItemName;
let text = "";
let i;
for (i = 0; i < cod.length; i++) {
text += cod[i] + "<br>";
}
document.getElementById("cod").innerHTML = text;
for (i = 0; i < name.length; i++) {
text += name[i] + "<br>";
}
document.getElementById("name").innerHTML = text;
},
init: function() {
util.ajax(settings.serviceAddress + "OITM", ctrl.showDados);
}
};
$(document).ready(function() {
ctrl.init();
});
<div class="container">
<table class="table table-hover">
<thead>
<tr>
<th>Código</th>
<th>Nome</th>
</tr>
</thead>
<tbody>
<tr>
<td id="cod">FSE0204</td>
<td id="name">25130101_Loc.Finaneira - BCP- CT 400105814</td>
</tr>
<tr>
<td>FSE0205</td>
<td>25130201_Loc.Finaneira - Totta- CT 195649</td>
</tr>
</tbody>
</table>
</div>

Iterate over table cells, re-using rowspan values

I have a simple HTML table, which uses rowspans in some random columns. An example might look like
A | B |
---|---| C
D | |
---| E |---
F | | G
I'd like to iterate over the rows such that I see rows as A,B,C, D,E,C, then F,E,G.
I think I can probably cobble together something very convoluted using cell.index() to check for "missed" columns in later rows, but I'd like something a little more elegant...
without jquery:
function tableToMatrix(table) {
var M = [];
for (var i = 0; i < table.rows.length; i++) {
var tr = table.rows[i];
M[i] = [];
for (var j = 0, k = 0; j < M[0].length || k < tr.cells.length;) {
var c = (M[i-1]||[])[j];
// first check if there's a continuing cell above with rowSpan
if (c && c.parentNode.rowIndex + c.rowSpan > i) {
M[i].push(...Array.from({length: c.colSpan}, () => c))
j += c.colSpan;
} else if (tr.cells[k]) {
var td = tr.cells[k++];
M[i].push(...Array.from({length: td.colSpan}, () => td));
j += td.colSpan;
}
}
}
return M;
}
var M = tableToMatrix(document.querySelector('table'));
console.table(M.map(r => r.map(c => c.innerText)));
var pre = document.createElement('pre');
pre.innerText = M.map(row => row.map(c => c.innerText).join('\t')).join('\n');
document.body.append(pre);
td {
border: 1px solid rgba(0,0,0,.3);
}
<table>
<tr>
<td colspan=2>A</td>
<td rowspan=2>B</td>
</tr>
<tr>
<td>C</td>
<td rowspan=3>D</td>
</tr>
<tr>
<td rowspan=2>E</td>
<td rowspan=4>F</td>
</tr>
<tr></tr>
<tr>
<td rowspan=2 colspan=2>G</td>
</tr>
<tr></tr>
<tr>
<td rowspan=3 colspan=3>H</td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td colspan=3>I</td>
</tr>
</table>
Try this:
<table id="tbl">
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td colspan="2" rowspan="2">A</td>
<td rowspan="2">C</td>
</tr>
<tr>
<td rowspan="2">E</td>
</tr>
<tr>
<td>F</td>
<td>G</td>
</tr>
</table>
Script:
var finalResult = '';
var totalTds = $('#tbl TR')[0].length;
var trArray = [];
var trArrayValue = [];
var trIndex = 1;
$('#tbl TR').each(function(){
var currentTr = $(this);
var tdIndex = 1;
trArray[trIndex] = [];
trArrayValue[trIndex] = [];
var tdActuallyTraversed = 0;
var colspanCount = 1;
$('#tbl TR').first().children().each(function(){
if(trIndex > 1 && trArray[trIndex - 1][tdIndex] > 1)
{
trArray[trIndex][tdIndex] = trArray[trIndex - 1][tdIndex] - 1;
trArrayValue[trIndex][tdIndex] = trArrayValue[trIndex - 1][tdIndex];
finalResult = finalResult + trArrayValue[trIndex][tdIndex];
}
else
{
if(colspanCount <= 1)
{
colspanCount = currentTr.children().eq(tdActuallyTraversed).attr('colspan') != undefined ? currentTr.children().eq(tdActuallyTraversed).attr('colspan') : 1;
}
if(colspanCount > 1 && tdIndex > 1)
{
trArray[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed + colspanCount).attr('rowspan') != undefined ?currentTr.children().eq(tdActuallyTraversed + colspanCount).attr('rowspan') : 1;
trArrayValue[trIndex][tdIndex] = trArrayValue[trIndex][tdIndex - 1];
colspanCount--;
}
else
{
trArray[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed).attr('rowspan') != undefined ?currentTr.children().eq(tdActuallyTraversed).attr('rowspan') : 1;
trArrayValue[trIndex][tdIndex] = currentTr.children().eq(tdActuallyTraversed).html();
tdActuallyTraversed++;
}
finalResult = finalResult + trArrayValue[trIndex][tdIndex];
}
tdIndex++;
});
trIndex++;
});
alert(finalResult);
Fiddle
i am not sure about the performance, but it works well.
what I understood with your question is: You want to split the merged cell with same value and then iterate the table simply by row.
I've created a JSFiddle that will split the merged cells with the same value. Then you'll have a table that can be iterated simply by rows to get the desired output that you specified.
See it running here http://jsfiddle.net/9PZQj/3/
Here's the complete code:
<table id="tbl" border = "1">
<tr>
<td>A</td>
<td>B</td>
<td rowspan="2">C</td>
</tr>
<tr>
<td>D</td>
<td rowspan="2">E</td>
</tr>
<tr>
<td>F</td>
<td>G</td>
</tr>
</table>
<br>
<div id="test"> </div>
Here's the jquery that is used to manipulate the table's data.
var tempTable = $('#tbl').clone(true);
var tableBody = $(tempTable).children();
$(tableBody).children().each(function(index , item){
var currentRow = item;
$(currentRow).children().each(function(index1, item1){
if($(item1).attr("rowspan"))
{
// copy the cell
var item2 = $(item1).clone(true);
// Remove rowspan
$(item1).removeAttr("rowspan");
$(item2).removeAttr("rowspan");
// last item's index in next row
var indexOfLastElement = $(currentRow).next().last().index();
if(indexOfLastElement <= index1)
{
$(currentRow).next().append(item2)
}
else
{
// intermediate cell insertion at right position
$(item2).insertBefore($(currentRow).next().children().eq(index1))
}
}
});
console.log(currentRow)
});
$('#test').append(tempTable);
You can use this Gist. It supports all the requirements by W3C, even "rowspan=0" (which seems to be only supported by Firefox).

How to count number of disabled columns in a table from javascript?

My table format is
<table class"tabletop">
<tr>
<td>
<table>
<tr>
<td id="mycol1"></td>
<td id="mycol2"></td>
<td id="mycol3"></td>
<td id="mycol4"></td>
</tr>
</table>
</td>
</tr>
<tr>
</tr>
</table>
I have to count columns(having id's) that are not disabled(or their display is not none) and that are disabled.
Suppose columns disabled are 4 and not disabled are 2.
So it must return disabled: 4 and not disabled: 2
td's are disabled by their id.
eg
mycol1.style.display="none";
Working Solution try this
<script type = "text/javascript" language = "javascript">
function getHiddenColumnCount() {
var tbl = document.getElementById("myTbl");
var HiddenColumnCount = 0;
for(var OuterCounter = 0 ; OuterCounter < tbl.rows.length ; OuterCounter++)
{
for(var InnerCounter = 0 ; InnerCounter < tbl.rows[OuterCounter].cells.length;InnerCounter++)
{
if (tbl.rows[OuterCounter].cells[InnerCounter].style.display == "none")
HiddenColumnCount++;
}
}
alert("There are " + HiddenColumnCount + " Hidden Columns in Table");
}
</script>
You can use
$('table td:visible').length
Try this: fiidle
<table border="1" id="myTbl">
<tr>
<td class="mycol1">
1
</td>
<td class="mycol2">
2
</td>
<td class="mycol3">
3
</td>
<td class="mycol4">
4
</td>
</tr>
</table>
<script>
function hideColumn(columnClass) {
var els = document.getElementsByClassName(columnClass);
for (var i = 0; i < els.length; i++) {
els[i].style.display = "none";
}
}
hideColumn('mycol1');
hideColumn('mycol2');
function getHiddenColumnsCount() {
var rows = document.getElementById('myTbl').rows;
var count = 0;
for (var i = 0; i < rows.length; i++) {
for (var j = 0; j < rows[i].cells.length; j++) {
if (rows[i].cells[j].style.display == "none")
count++;
}
}
alert(count);
}
getHiddenColumnsCount();
</script>
First of all you should use class for defining column instead of id as id should not be duplicate & to define a column we will have to give similar id to all cells of a column.

Replacing HTML content with dojo and javascript

Have made a table and stored it in a variale getcontent by using basic HTML.
getcontent="<table style="height: 1000px; ; width: 500px;" border="1">
<tbody>
<tr>
<td>[Assignment name]</td>
<td>[<span>Approximate Value of Contract</span>]</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>"
Contentinsquare is an array containg string which can be filled in th table. (SQUARE BRACKETS] in getcontent
contentinsquare=["name","100$"]
i want the value of contentinsqaure to be placed in between the sqaure brackets.For that i have used the code :-
var contentinsquare=["name","100$"]
var strInputCode = contentinsquare[1].replace(/&(lt|gt);/g, function (strMatch, p1){
return (p1 == "lt")? "<" : ">";
});
var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
contentinsquare[1]=strTagStrippedText
var strforlabelname = []
var strfortextarea = []
var strfortext = []
var str = []
label = dojo.query('label');
console.log(label, "all label names")
for( i = 0; i < label.length; i++)
{
if(label[i].id != "")
{
inner = dojo.byId(label[i].id).innerHTML
var name = inner.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
strforlabelname.push(name)
}
}
console.log(strforlabelname, "string")
text = dojo.query('input')
for( i = 0; i < text.length; i++)
{
if(text[i].id == "")
{
}
else
{
innertext = dijit.byId(text[i].id).getValue();
str.push(innertext)
//console.log(str,"strng1")
}
}
textarea = dojo.query('textarea')
for( i = 0; i < textarea.length; i++)
{
if(textarea[i].id == ""||textarea[i].id =="textareaidfirst")
{
}
else
{
innertextarea = dojo.byId(textarea[i].id).value
str.push(innertextarea)
}
}
for( i = 0; i < strforlabelname.length; i++)
{
for( j = 0; j < contentinsquare.length; j++)
{
if(contentinsquare[j] == strforlabelname[i])
{
var patt = new RegExp("\\[" + strforlabelname[i] + "\\]", "g")
getcontent = getcontent.replace(patt, str[i]);
}
}
}
This results to :-
Result :-
"<table style="height: 1000px; ; width: 500px;" border="1">
<tbody>
<tr>
<td>name</td>
<td>[<span>Approximate Value of Contract</span>]</td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</tbody>
</table>"
that is the sqaure brackets contaning <span> tag is not working. i want the 100 $ to be replaced over thr.

Categories

Resources