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.
Related
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>
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 tried doing the necessary but cannot get a single image to appear broken up into 16 pieces. here is my code to the original with no image and works with the numbers 1-15
<?xmlversion="1.0"encoding="utf-8"?>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!--Exercise12.8:Solution-->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Solution12.8</title>
<style type="text/css">
span{font-size:4em;
font-weight:bold;
font-family:helvetica,arial,sans-serif;
color:blue}
table{border-collapse:collapse}
td{border:2px solid gray;
width:5em}
</style>
<script type="text/javascript">
<!--
var cells;
var swapped;
function setup()
{
// create a 2d array of all the cells
cells = new Array(
[ document.getElementById("cell00"),
document.getElementById("cell01"),
document.getElementById("cell02"),
document.getElementById("cell03") ],
[ document.getElementById("cell10"),
document.getElementById("cell11"),
document.getElementById("cell12"),
document.getElementById("cell13") ],
[ document.getElementById("cell20"),
document.getElementById("cell21"),
document.getElementById("cell22"),
document.getElementById("cell23") ],
[ document.getElementById("cell30"),
document.getElementById("cell31"),
document.getElementById("cell32"),
document.getElementById("cell33") ] );
placeNumbers();
}
function placeNumbers()
{
var numbers = new Array();
var randomLoc;
var temp;
for(var i=0; i < 16;i++)
numbers[i]= i;
for(i = 0; i <16;i++)
{
randomLoc = Math.floor(Math.random()*15+1);
temp = numbers[i];
numbers[i] = numbers[randomLoc];
numbers[randomLoc] = temp;
}
i=0;
for (var rows=0;rows<4;rows++)
for(var cols = 0;cols<4;cols++)
{
if ( numbers[i] != 0)
cells[rows][cols].innerHTML = numbers[i];
else
cells[rows][cols].innerHTML="";
++i;
}
}
function doClick(row,col)
{
var top = row-1;
var bottom = row + 1;
var left = col - 1;
var right = col + 1;
swapped = false;
if (top != -1 && cells[top][col].innerHTML=="")
swap(cells[row][col], cells[top][col]);
else if ( right != 4 &&
cells[row][right].innerHTML =="")
swap(cells[row][col],cells[row][right]);
else if (bottom != 4 &&
cells[bottom][col].innerHTML == "")
swap (cells[row][col],cells[bottom][col]);
else if ( left != -1 &&
cells[row][left].innerHTML=="")
swap(cells[row][col],cells[row][left]);
else
alert("An Illegal move has been made. Please click on a number nearest the blank space");
checkWin();
}
function swap(firstCell,secondCell)
{
swapped = true;
secondCell.innerHTML=firstCell.innerHTML;
firstCell.innerHTML="";
}
function checkWin()
{
var win = true;
for (var i = 0 ; i < 4; i++)
for (var j = 0; j < 4; j++)
if (!(cells[i][j].innerHTML == i*4 + j + 1))
if (!(i == 3 && j == 3))
win = false;
if (win)
if ( window.prompt( "Would you like to play again?", "yes") )
placeNumbers();
else
alert ("Game Over. Thank you for playing");
}
//-->
</script>
</head>
<body onload="setup()">
<table>
<tr>
<td> <span onclick = "doClick(0,0)"id="cell00"/></td>
<td> <span onclick = "doClick(0,1)"id="cell01"/></td>
<td> <span onclick = "doClick(0,2)"id="cell02"/></td>
<td> <span onclick = "doClick(0,3)"id="cell03"/></td>
</tr>
<tr>
<td> <span onclick = "doClick(1,0)"id="cell10"/></td>
<td> <span onclick = "doClick(1,1)"id="cell11"/></td>
<td> <span onclick = "doClick(1,2)"id="cell12"/></td>
<td> <span onclick = "doClick(1,3)"id="cell13"/></td>
</tr>
<tr>
<td> <span onclick = "doClick(2,0)"id="cell20"/></td>
<td> <span onclick = "doClick(2,1)"id="cell21"/></td>
<td> <span onclick = "doClick(2,2)"id="cell22"/></td>
<td> <span onclick = "doClick(2,3)"id="cell23"/></td>
</tr>
<tr>
<td> <span onclick = "doClick(3,0)"id="cell30"/></td>
<td> <span onclick = "doClick(3,1)"id="cell31"/></td>
<td> <span onclick = "doClick(3,2)"id="cell32"/></td>
<td> <span onclick = "doClick(3,3)"id="cell33"/></td>
</tr>
</table>
</body>
</html>
Now I am trying for the image here is the code but i cannot get it to work...
<html>
<head>
<title>12.9</title>
<style type = "text/css">
table{border-collapse:collapse}
td{border:1px solid gray;}
</style>
<script type= "text/javascript">
<--
var cells;
var swapped;
function setup()
{
//create a 2d array of cells
cells = new Array (
[ document.getElementById("cell00"),
document.getElementById("cell01"),
document.getElementById("cell02"),
document.getElementById("cell03")],
[ document.getElementById("cell10"),
document.getElementById("cell11"),
document.getElementById("cell12"),
document.getElementById("cell13")],
[ document.getElementById("cell20"),
document.getElementById("cell21"),
document.getElementById("cell22"),
document.getElementById("cell23")],
[ document.getElementById("cell30"),
document.getElementById("cell31"),
document.getElementById("cell32"),
document.getElementById("cell33") ] );
placeNumbers();
}
function placeNumbers()
{
var numbers = new Array();
var randomLoc;
var temp;
for (i= 0; i < 16; i++)
numbers[i] = i + "9.gif";
for (i=0; i<16; i++)
{
randomLoc = Math.floor( Math.random() * 15 + 1 );
temp = numbers[i];
numbers[i] = numbers[randomLoc];
numbers[randomLoc] = temp;
}
i = 0;
for (var rows = 0; rows < 4; rows++)
for ( vars cols = 0; cols < 4; cols++;)
{
if (numbers [i] != "9.gif")
{
cells[rows][cols].src = numbers[i];
cells[rows][cols].alt = numbers[i];
}
else
{
cells[rows][cols].style.display = "none";
cells[rows][cols].alt = "hidden";
cells[rows][cols].src = "9.gif";
}
++i;
}
}
function doClick( row, col)
{
var top = row - 1;
var bottom = row + 1;
var left = col - 1;
var right = col + 1;
swapped = false;
if ( top != -1 && cells[top][col].alt == "hidden")
swap (cells[row][col], cells[top][col]);
else if (right != 4 &&
cells [row][right].alt == "hidden")
swap (cells[row][col], cells[row][right] );
else if (bottom != 4 &&
cells[bottom][col].alt == "hidden")
swap(cells[row][col], cells[bottom][col]);
else if (left != -1 &&
cells[row][left].alt == "hidden")
swap( cells[row][col], cells[row][left]);
else
alert( "Illegal Move has been made" );
checkWin();
}
function swap(firstCell, secondCell)
{
swapped = true;
secondCell.src = firstCell.src;
secondCell.alt = firstCell.alt;
secondCell.style.display = "inline";
firstCell.src = "9.gif";
firstCell.alt = "hidden";
firstCell.style.display = "none";
}
function checkWin()
{
var win = true;
for(var i = 0; i<4; i++)
for (var j = 0; j<4; j++)
if (!(cells[i][j].src == i*4 + j + 1 + "9.gif"))
if (!(i == 3 && j == 3) )
win = false;
if (win)
if ( window.prompt( "Would you like to play again?", "yes") )
placeNumbers();
}
//-->
</script>
</head>
<body onload = "setup()">
<table>
<tr>
<td><img src = "9.gif" alt = "" onclick = "doClick(0,0)"
id = "cell00" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(0,1)"
id = "cell01" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(0,2)"
id = "cell02" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(0,3)"
id = "cell03" /></td>
</tr>
<tr>
<td><img src = "9.gif" alt = "" onclick = "doClick(1,0)"
id = "cell10" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(1,1)"
id = "cell11" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(1,2)"
id = "cell12" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(1,3)"
id = "cell13" /></td>
</tr>
<tr>
<td><img src = "9.gif" alt = "" onclick = "doClick(2,0)"
id = "cell20" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(2,1)"
id = "cell21" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(2,2)"
id = "cell22" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(2,3)"
id = "cell23" /></td>
</tr>
<tr>
<td><img src = "9.gif" alt = "" onclick = "doClick(3,0)"
id = "cell30" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(3,1)"
id = "cell31" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(3,2)"
id = "cell32" /></td>
<td><img src = "9.gif" alt = "" onclick = "doClick(3,3)"
id = "cell33" /></td>
</tr>
</table>
</body>
</html>
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).
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.