Yesterday I asked a question and, "with a little help from my friends" got my little javascript working.
This one:
<script type="text/javascript" >
function paint_cells() {
var tds = document.querySelectorAll('tbody td'), i;
for(i = 0; i < tds.length; i += 3) {
if(tds[i+1].textContent != tds[i+2].textContent){
tds[i+2].bgColor = "red";
}
}
}
paint_cells();
</script>
Now I would like to tweak this to cater for multiple correct answers. For example, both
'don't hurry' or 'do not hurry' are correct. In my MySQL table, they are stored as a string like this:
don't hurry|do not hurry
I want to split the string on | and then check if the student's answer is in the array (same as I do in PHP when marking the answers).
Not all answers have multiple correct answers. I hope that is not a problem for .split()??
I tried this, but I am not getting the result I want. Can you please help me tweak this to give me the result I want?
Edit: I thought maybe the apostrophes were causing the problem, so I escaped them. I trimmed each variable.
But I still don't get what I want! Any tips please?
<script type="text/javascript" >
function paint_cells() {
var tds = document.querySelectorAll('tbody td'), i;
for(i = 0; i < tds.length; i += 3) {
var arr = tds[i+1].textContent.split('|');
for(j = 0; j < arr.length; j++) {
arr[j].trim();
arr[j].replace(/'/g, "\'");
}
var myvar = tds[i+2].textContent;
myvar.trim();
myvar.replace(/'/g, "\'");
//console.log("Your line would be here")//Prints a line on the console
if(!arr.includes(myvar)){
//if(arr[0] != myvar){
alert('Array length: ' + arr.length + ' Answers: ' + tds[i+1].textContent + ' Student answer:' + myvar);
tds[i+2].bgColor = "red";
}
}
}
paint_cells();
</script>
Quotes don't matter. You have to reset the array to the trimmed value... trim returns the modified value, it doesn't "change in place".
var arr = answers.split('|');
for(var ii=0; ii<arr.length; ii++){
arr[ii] = arr[ii].trim().toLowerCase();
}
Here's a working example (run code snippet below):
function paint_cells() {
var tds = document.querySelectorAll('tbody td');
for (var i = 0; i < tds.length; i += 3) {
var cell_1 = tds[i + 1];
var cell_2 = tds[i + 2];
var answers = cell_1.textContent;
var arr = answers.split('|');
for (var ii = 0; ii < arr.length; ii++) {
arr[ii] = arr[ii].trim().toLowerCase();
}
var guess = (cell_2.textContent || "").trim().toLowerCase();
//console.log("Your line would be here")//Prints a line on the console
if (arr.indexOf(guess) < 0) {
console.log('Array length: ' + arr.length + ' Answers: ' + answers + ' Student answer:' + cell_2.textContent);
cell_2.style.backgroundColor = "red";
}
}
}
paint_cells()
<table>
<tbody>
<tr>
<td></td>
<td>don't hurry|do not hurry</td>
<td>do not hurry</td>
</tr>
<tr>
<td></td>
<td>don't hurry|do not hurry</td>
<td>don't hurry</td>
</tr>
<tr>
<td></td>
<td>don't hurry|do not hurry</td>
<td>abc</td>
</tr>
<tr>
<td></td>
<td>don't hurry|do not hurry</td>
<td>xyz</td>
</tr>
</tbody>
</table>
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>
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>
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).
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.