Javascript calculation is not working as expected - javascript

I have a gridview in which there is a row in which I add integer values like 7000.
So if there are 2-3 rows added, I want to add all those rows values and show it in the textbox
So for that, I have written the below code
if (document.getElementById('txtTotalExp').value == "") {
var Expense = 0;
} else {
var Expense = document.getElementById('txtTotalExp').value;
}
for (var i = 0; i < GridExpInfo.Rows.length; i++) {
var totAmount = GridExpInfo.Rows[i].Cells[7].Value;
var totval = totAmount;
Expense += parseInt(totval);
}
document.getElementById('txtTotalLandVal').value = parseInt(TotalPayableValue) + parseInt(Expense);
But In the textbox it is coming something like this
200010001512
The addition operation is not working.

I interpret your question to mean that you have a table with rows of values, you want to sum each row, and then you want to get a total sum-of-the-row-sums for the entire table.
I wanted to provide a working code snippet to demonstrate a solution to your problem. However, because you didn't provide all the necessary code, I invented some of it. In the process of doing so, I provided an alternative, and perhaps more modern, approach to solving the overall problem I think you were trying to solve. Yes, it's providing significantly more than what you were asking for (...I think some of the other answers that discuss parseInt might solve your initial problem) but hopefully this gives you some further insight.
The example below shows how to do this using many recent features of JavaScript. Hopefully the comments explain what is happening at every step in enough detail that you get a sense of the logic. To understand each step, you are probably going to have dig deeper into learning more JavaScript. A good reference is the Mozilla Developer Network (MDN), which contains documentation on all these features.
// when the button is clicked, do the following...
document.querySelector('button').onclick = () => {
// calculate the total sum across the table
const rowSums =
// get a nodeList of all table rows in the entire document
// and convert that array-like nodeList to a true array
// of table row elements
[...document.querySelectorAll('tr')]
// remove the first row, i.e. ignore the row of column headers
.slice(1)
// from the original array of table rows (minus the first row)
// create a new array in which each element is derived
// from the corresponding table row from the original array
.map(row => {
// calculate the sum of values across this row
const rowSum =
// get a nodeList of all table cells in this row
// and convert that array-like nodeList to a true array
// of table cell elements
[...row.querySelectorAll('td')]
// remove the last cell, i.e. ignore the cell that will eventually
// hold the sum for this row
.slice(0,-1)
// from the array of table cells for this row (minus the last one)
// derive a new single value by progressively doing something
// for each cell
.reduce(
// for each table cell in this row, remember the cell itself
// as well as the accumulating value we are gradually deriving from all
// the cells in this row, i.e. the sum of all values across this row
(accumulatingRowSum, cell) =>
// for each cell in this row, add the numerical value
// of the current cell to the sum of values we are accumulating
// across this row
accumulatingRowSum + parseInt(cell.innerHTML, 10),
// start our accumulating sum of values across this row with zero
0
);
// get all the cells in this row
const rowCells = row.querySelectorAll('td');
// put the sum of values from this row into the last cell of the row
rowCells[rowCells.length - 1].innerHTML = rowSum;
// place the sum of values in this row into the accumulating array
// of all such values for all rows
return rowSum;
});
// calculate the total sum for the whole table
const totalExpenses =
// start with the array of sums for each row
rowSums
// similar to `reduce` above, reduce the array of multiple row sums
// into a single value of the total sum, calculated by adding together
// all the individual row sums, starting with zero
.reduce((accumulatingTotalSum, rowTotal) => accumulatingTotalSum + rowTotal, 0);
// place the total sum into the appropriate span element
document.querySelector('#txtTotalExp').innerHTML = totalExpenses;
};
table {
border: solid black 1px;
border-collapse: collapse;
}
th, td {
border: solid black 1px;
padding: 0.5em;
}
<table>
<tr><th>col1</th><th>col2</th><th>row total</th></tr>
<tr><td>3500</td><td>1200</td><td></td></tr>
<tr><td>2700</td><td>4500</td><td></td></tr>
<tr><td>3100</td><td>1300</td><td></td></tr>
</table>
<p>The total expenses are: <span id="txtTotalExp"></span></p>
<button>Calculate</button>

you can used below code:
var total=parseInt(TotalPayableValue,10) + parseInt(Expense,10);
document.getElementById('txtTotalLandVal').value=total;

try this:
var Expense = 0;
if (document.getElementById('txtTotalExp').value != "") {
var Expense = parseInt(document.getElementById('txtTotalExp').value);
}
for (var i = 0; i < GridExpInfo.Rows.length; i++) {
var totAmount = GridExpInfo.Rows[i].Cells[7].Value;
Expense += parseInt(totAmount);
}
The problem: Expense initially can be a string. Have you tried if with "Expense = 0" the error occurs?

Related

Is it possible to pull different data sets from one column?

I've been trying to write some code that looks down one column with strings based on some simple formulas. I can't seem to get it to recognize the different sets of data and paste them where I want them.
I have tried re writing the code a few different ways in which is looks at all the data and just offsets the destination row by 1. But it does not recognize that it is pull different data.
Below is the code that works. What it does is starts from the 1st column 2nd row (where my data starts). The data is a list like;
A
1 Customer1
2 item1
3 item2
4 Item3
5
6 Customer2
7 Item1
The formulas that I have in those cells just concatenates some other cells.
Using a loop it looks through column A and find the blank space. It then "breaks" whatever number it stops on, the numerical A1 notation of the cell, it then finds the values for those cells and transposes them In another sheet in the correct row.
The issue I am having with the code this code that has worked the best is it doesn't read any of the cells as blank
(because of the formulas?) and it transposes all to the same row.
function transpose(){
var data = SpreadsheetApp.getActiveSpreadsheet();
var input =data.getSheetByName("EMAIL INPUT");
var output = data.getSheetByName("EMAIL OUTPUT");
var lr =input.getLastRow();
for (var i=2;i<20;i++){
var cell = input.getRange(i, 1).getValue();
if (cell == ""){
break
}
}
var set = input.getRange(2, 1, i-1).getValues();
output.getRange(2,1,set[0].length,set.length) .
.setValues(Object.keys(set[0]).map ( function (columnNumber) {
return set.map( function (row) {
return row[columnNumber];
});
}));
Logger.log(i);
Logger.log(set);
}
What I need the code to do is look through all the data and separate the sets of data by a condition.
Then Transpose that information on another sheet. Each set (or array) of data will go into a different row. With each component filling across the column (["customer1", "Item1","Item2"].
EDIT:
Is it Possible to pull different data sets from a single column and turn them into arrays? I believe being able to do that will work if I use "appendrow" to tranpose my different arrays to where I need them.
Test for the length of cell. Even if it is a formula, it will evaluate the result based on the value.
if (cell.length !=0){
// the cell is NOT empty, so do this
}
else
{
// the cell IS empty, so do this instead
}
EXTRA
This code takes your objective and completes the transposition of data.
The code is not as efficient as it might/should because it includes getRange and setValues inside the loop.
Ideally the entire Output Range could/should be set in one command, but the (unanswered) challenge to this is knowing in advance the maximum number rows per contiguous range so that blank values can be set for rows that have less than the maximum number of rows.
This would be a worthwhile change to make.
function so5671809203() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var inputsheetname = "EMAIL_INPUT";
var inputsheet = ss.getSheetByName(inputsheetname);
var outputsheetname = "EMAIL_OUTPUT";
var outputsheet = ss.getSheetByName(outputsheetname);
var inputLR =inputsheet.getLastRow();
Logger.log("DEBUG: the last row = "+inputLR);
var inputrange = inputsheet.getRange(1, 1,inputLR+1);
Logger.log("the input range = "+inputrange.getA1Notation());
var values = inputrange.getValues();
var outputval=[];
var outputrow=[];
var counter = 0; // to count number of columns in array
for (i=0;i<inputLR+1;i++){
Logger.log("DEBUG: Row:"+i+", Value = "+values [i][0]+", Length = "+values [i][0].length);
if (values [i][0].length !=0){
// add this to the output sheet
outputrow.push(values [i][0]);
counter = counter+1;
Logger.log("DEBUG: value = "+values [i][0]+" to be added to array. New Array Value = "+outputrow+", counter = "+counter);
}
else
{
// do nothing with the cell, but add the existing values to the output sheet
Logger.log("DEBUG: Found a space - time to update output");
// push the values onto an clean array
outputval.push(outputrow);
// reset the row array
outputrow = [];
// get the last row of the output sheet
var outputLR =outputsheet.getLastRow();
Logger.log("DEBUG: output last row = "+outputLR);
// defie the output range
var outputrange = outputsheet.getRange((+outputLR+1),1,1,counter);
Logger.log("DEBUG: the output range = "+outputrange.getA1Notation());
// update the values with array
outputrange.setValues(outputval);
// reset the row counter
counter = 0;
//reset the output value array
outputval=[];
}
}
}
Email Input and Output Sheets

HTML Table and JavaScript addRows and addColumns without jQuery?

I'm having a problem getting the buttons on my student grades table working, I have a button to calculate the average of the grades using a function called getAverage(), I have one to insert rows to the table using a function called insert_Rows, and finally one to add columns using a function called insert_Column().
My problem is that none of them seem to be working and I can't see why the getAverage function was working until I added the other two buttons.
This is for an assignment where I'm not allowed to use jQuery.
Also, this is the brief for the two buttons:
A CSS styled button that inserts a new table row suitable for recording new student data. You can insert after the last row of the table. Students should provide on button that saves the table in its current state i.e. if there are 5 rows and 6 cells, the cookie should reflect that.
A CSS style button that inserts a new table column suitable for recording new Assignment grade data. This column requires a title. You can decide how you wish to accomplish the title allocation (automatic, content-edit, etc.). There should be another button that then retrieves that data and fills it back to the table in the state that it previously held. If extra rows or columns have been added, the table should revert back to its previous state when the cookie was saved (5 rows and 6 cells).
Also, for extra credit, I have to use JavaScript and any method of my choosing to delete a data row selected by a user, and another on to delete an assignment column selected by the user, the function should ensure that the final grade column totals are updated following this deletion.
// get the average
function getAverage()
{
let table = document.getElementById("gradesTable");
//Loop over the rows array directly
let rows = Array.prtotype.slice.call(table.rows); //let is block scoped - can only be used in this block
rows.froEach(function(row)
{
let cells = array.protoype.slice.call(row.querySelectorAll(".Assignment")); // Get all the Assignment cells into an array
// declairing sum and gradeAverage with let and by defining them in the row loop keeps the values unique for each row
let sum = 0;
let gradeAverage = 0;
// Now just loop the cells Array
cells.forEach(function(cell,index){
//.textContent instead for strings that dont contain any values
var currentValue = parseInt(cell.textContent);
if(currentValue >= 0 && currentValue <=100){
sum += currentValue;
}
// If the cell has "-" for content
if(cell.textContent === '"-"'){
// Apply a pre-made CSS class
cell.classList.add("noGrade");
} else {
// Remove a pre-made CSS class
cell.classList.remove("noGrade");
}
// If this is the last cell in the row
if(index === cells.length-1){
gradeAverage = sum/5;
cell.nextElementSibling.textContent = Math.round(gradeAverage) + "%";
// There is a grade, so check it for low
if(gradeAverage >= 0 && gradeAverage < 40) {
cell.nextElementSibling.classList.add("lowGrade");
} else {
cell.nextElementSibling.classList.remove("lowGrade");
}
}
});
});
}
// add a row to the table
function insert_Row() {
let table = document.getElementById("gradesTable"); //assign table id to a variable
let tableRows = table.rows.length; // gives how many rows in the table
let row = table.insertRow(tableRows); //insert after the last row in the table
let cellsInTable = document.getElementById("gradesTable").rows[0].cells
let columnTotal = cellsInTable.length; //assign the columnTotal the number of columns that the first row has
//loop through each column
for(let i = 0; i < columnTotal; i++)
{
//add a new cell for each column
let cell = row.insertCell(i);
//assign each new cell the default value "-"
cell.innerHTML = "-";
}
}
// add a column to the HTML table
function appendColumn()
{
let table = document.getElementById("gradesTable"); // table reference
// open loop for each row and append cell
for(let x = 0; x < table.rows.length; x++)
{
createCell(tbale.rows[x].insertCell(table.rows[x].cells.lenght), x, "col");
}
}
function insert_Column()
{
}
function deleteColumn()
{
let allRows = document.getElementById("gradesTable").rows;
for (var i=0; i < allRows.length; i++)
{
if (allRows[i].cells.length > 1)
{
allRows[i].deleteCell(-1);
}
}
}
Correction, the Insert row function seems to be working right, but the grades average function isn't and I don't know where to begin writing the other functions.
If anyone can offer advice or best places to learn? Because my lecturer has just informed us to use W3Schools and he's not teaching us the language, I just feel out of my depth.

Excel Online Add-in - Adding rows with a function as the value for the first column creates a total row

Having a weird issue with the Excel Online JS Api. I'm creating a new sheet and adding a table with data from an API call. There is a specific case where the first column of the table has a hyperlink function ('=HYPERLINK("somelink", "Go to Wherever")') and after it is being added to the table.rows, one of the rows is being created as the total row.
It always picks the same row to be the total row for the same set of data, but will pick a different row between sets of data. So, it's not always the same index being used.
Here is a snippet of how I'm adding the rows. It's pretty straight forward:
.then(function(){
var dataTable = ctx.workbook.tables.add(topLeftCell.address + ':' + topRightCell.address.split('!')[1], true);
var headers = data[0];
var headerRange = dataTable.getHeaderRowRange();
headerRange.values = [headers];
for (i = 1; i < data.length; i++) {
if (!data[i] || data[i].length !== data[i - 1].length) {
break;
}
dataTable.rows.add(-1, [data[i]]);
}
dataTable.getRange().format.autofitColumns();
return util.ctxSync(ctx);
})
.then(function(){
worksheet.activate();
return util.ctxSync(ctx);
})
The worksheet and the table create just fine, but having any formula as the first value in the row will cause one row to be created as the table's total row instead of a normal row. It can get gotten with dataTable.getTotalRowRange(), but is not in dataTable.rows. It's strange.
I've assumed this is an Excel bug and I can fix it by adding a dummy column with any value that isn't a formula as the first column and then deleting it before the autofitColumns().
Would anyone have any ideas towards a better fix? Any insight is appreciated.

Loops to remove rows and add rows in the same spreadsheet won't run correctly

I have been working on a script that adds and deletes rows from a number of spreadsheets according to values in an ID column.
In a master sheet,
If the first column has New Student...add the ID of the student above to an array.( so we can loop for these IDs in the sheets and add a row under them)
If the first column has Remove Student...add the ID of the student in
this row to an array.(so we can delete these rows from the sheets)
Ex. of Master Student List:
Ex. of data sheet:
My script loops through all the spreadsheets in a folder properly. My issue is with my loops that add and remove rows. If they both run on the same sheet, they mess everything up. I have both loops looping backward through the values in the ID column and through the arrays to try and stop it from grabbing the wrong rows being that it's adding and deleting them as it goes. But' they are not working.
Both of the loops work perfectly if they are run independently. Its when one loop has to remove students and the other has to add rows for students that it removes the wrong student row and adds the row in the wrong place etc. I know it has to do with my syntax in the loops, but I am not very good with them. Any advice you guys can give would be greatly appreciated. even if it means taking a different approach to the whole process. I only added the code below that loops through each spreadsheet, being that the rest is working properly. I hope this makes sense. I can add the rest of the code if it helps, I just know we are suppose to stay specific on here. Thanks so much! Brandon
ssName = thisSS.getName(),
ssUrl = thisSS.getUrl(),
archiveSS = SpreadsheetApp.openById('Archive Spreadsheetheet ID'), //Data Report Sheet ID
archiveSheet = archiveSS.getSheets()[0],
archiveSheetNewRow = archiveSheet.getLastRow(),
archiveNewRow = archiveSheet.getLastRow() + 1,
dataReportRange = archiveSheet.getRange(archiveNewRow,1,1,1);
Logger.log("New student array after break - " + AboveNewStudentArr);
Logger.log("Archive student array after break - " + archiveStudentArr);
/*---------------Loops---------------*/
/* If file is in filesToExclude skip it, if not proceed */
if (filesToExclude.indexOf(ssName)!==-1) {
} else {
/* Array of values for loops below */
var k, t, addRowArray = AboveNewStudentArr; //AboveNewStudentArr - is ths array of Ids to place a new row below
var addRowArrayLen = addRowArray.length;
/* Loop through the addRowArray aray */
for (var k = addRowArrayLen-1; k>=0 ;k--) {
/* Loop through the idRange */
for(var l = idRange.length-1; l>0 ; l--){
/* If value in idRange matches value in addRowArray, add a row below it */
if (idRange[l] == addRowArray[k]) {
var rowFormulas = classData.getRange(l+1,1,1,classData.getLastColumn()).getFormulas();
thisSS.insertRowAfter(l+1).getRange(l+2,1,1,classData.getLastColumn()).setFormulas(rowFormulas);
Logger.log("Added row for student with ID# " + t);
}
}
}
/* Array of values for loops below */
var i, s, removeStudent = archiveStudentArr; //archiveStudentArr - is ths array of Ids of rows to remove
var arrayLength = removeStudent.length;
/* Loop through the removeStudent aray */
for (var i = arrayLength-1; i>=0 ;i--) {
s = removeStudent[i];
/* Loop through the idRange */
for(var j = idRange.length-1; j>0 ; j--){
/* If value in idRange matches value in removeStudent, remove the row */
if (idRange[j] == removeStudent[i]) {
var row = Number(j)+1;
var lastColumn = classData.getLastColumn()
classData.deleteRow(row);
Logger.log("Removed student with ID# " + s + " by deleting row " + row);
}
}
}
For complex work flows, it's good to have separate functions that do generic tasks, and keep the main function as short as possible with just the decision making logic. That way, it's easier to think through how the program is flowing.
So, the first thing I recommend, is to create separate functions for populating the arrays, and doing any tasks. Only have decision making code in the main function.
Main Function:
function mainLogicForStudentIDs() {
//Process either the addition or deletion of rows first, independently.
//Find any rows that need to be removed
var rtrnInfoFromTheFindRemoveFnc = fncToFindRowsToRemove();
if (rtrnInfoFromTheFindRemoveFnc !== false) {
fncToRemoveRows(rtrnInfoFromTheFindRemoveFnc);
};
//Find any rows with new students
var rtrnInfoFromTheFindNewStudentsFnc = fncNewStudents();
if (rtrnInfoFromTheFindNewStudentsFnc !== false) {
fncProcessNewStudents(rtrnInfoFromTheFindNewStudentsFnc);
};
};
Separate Function to Find rows to Remove.
function fncToFindRowsToRemove() {
var arrayOfRowsToDelete = [];
for () {}; //Build the array of rows to delete
if (arrayOfRowsToDelete.length === 0) {
return false;
} else {
return arrayOfRowsToDelete;
};
};
Remove the Rows
function fncToRemoveRows(arrayPassedIn) {
//Loop through all rows to delete, and delete them.
};
If your code works independently correct, issue might be on indexes of arrays since array length is keep changing. so after you add new row and before you remove a row, you need to initiate idRange array.
/* Loop through the addRowArray array */
***********
idRange = //re initiate this array
********
/* Loop through the removeStudent array */

Accessing a dynamically created variable in a dynamic way

This may take a bit of explaining, so please bear with me.
I'm trying to create X number of tables, each of a varying length (columns) Y, with 4 rows each, X and Y being determined by the user. This part I have solved.
The problem is that every cell in every table must contain it's own text box, which will contain numbers derived from a database. If the user changes the number in the text box, the change must then be reflected in the database.
Given that the number of tables and the length of the tables are unknown, I can't set up the names of the text boxes ahead of time and must do so dynamically.
I ran across this code:
var pageNumber = 1;
eval("var text" + pageNumber + "=123;");
alert(text1);
//alert shows '123'
Which (with modification), I believe would allow me to dynamically create a unique name for each text box. What I am having trouble with is how do I then access this new text box since I don't know what it's called(after the table has been created)?
I plan on using a 3d array to hold the numbers that I want displayed in each cell in the table and plan to use this array to name the cell.
As an example the array could be array[i][j][k], and lets say i=1, j=2, k=3, which would hold the number 8.
The dynamically created text box name would be something like:
textBox123
How do I associate that cell in the array (containing 8) with that new text box and then retrieve and store a new value when I don't know it's name ahead of time?
The way I'm thinking of it, how do I write something like
<input type="text" name="textBox123" value=array[i][j][k]>
to the html?
Then again, maybe I'm over thinking this and there is a better way of doing it. If so, please let me know.
HTML:
<div id="tables"></div>
JavaScript:
var tables = [
// Table #1
[
[111, 112, 113], // Row #1
[121, 122, 123] // Row #2
],
// Table #2
[
[211, 212, 213, 214], // Row #1
[221, 222, 223, 224], // Row #2
[231, 232, 233, 234] // Row #3
],
// Table #3 (empty!)
[]
],
nr, nc, i, j, k,
name, value, textBox, cell, row, table,
$tables = $("#tables");
for (i = 0; i < tables.length; ++i) {
nr = tables[i].length;
nc = nr > 0 ? tables[i][0].length : 0;
table = "<table>";
for (j = 0; j < nr; ++j) {
row = "<tr>";
for (k = 0; k < nc; ++k) {
name = "textBox" + (i + 1) + (j + 1) + (k + 1);
value = tables[i][j][k];
textBox = "<input type='text' name='" + name + "' value='" + value + "'>";
cell = "<td>" + textBox + "</td>";
row += cell;
}
row += "</tr>\n";
table += row;
}
table += "</table>\n";
$tables.append(table);
}
See the jsfiddle. The 3rd, empty table will be inserted as an empty table tag, but this is not necessary.
I would like to mention that since you need to connect these tables to a database, an elegant solution would be using a client-side MVC framework, like Backbone.js. Here you find a good intro book. The View could use a code similar to the one above to render the tables. The tables array could be stored in a Collection.
You don't have to pre-tag every cell in the table with its index because you can calculate it based on the DOM hierarchy upon demand.
If you have an arbitrary cell in a table, you can get the row and column number of that cell in the table like this where cell as passed to this function can either be the td object or any descendant of it (such as your <input> tag that's in the table):
// Pass any td object or descendant of a td object in a <table> and it will return
// an object with {row: x, col: y}
// or return null if the cell passed wasn't inside a <tr> and <td>
function findRowColInTable(cell) {
function findParent(obj, parentTagName) {
parentTagName = parentTagName.toUpperCase();
while (obj && obj.tagName != parentTagName) {
obj = obj.parentNode;
}
return obj;
}
findChildCnt(obj) {
var cnt = 0;
while (obj = obj.prevSibling) {
++cnt;
}
return cnt;
}
var td, tr, col, row;
// get table cell
td = findParent(cell, "TD");
if (td) {
col = findChildCnt(td);
tr = findParent(td, "TR");
if (tr) {
row = findChildCnt(tr);
return {row: row, col: col};
}
}
return null;
}
FYI, this is quite a bit easier in jQuery where you can use .closest(tag) and .index() to find appropriate parents and get your local sibling count, but I've offered you a pure javascript version.
You can actually do arrays on forms. Take my old answer for example, you can create arrays in form inputs with such naming scheme. On the back-end, you get them as arrays (Assuming PHP).
If you are grabbing the values via JS instead, you can base it off this answer, which takes advantage of the naming scheme, grabs the form values and turns them into JS objects and arrays similar to how PHP would receive them on the back-end. Basically it runs through the form and gets the form values. It's partly jQuery, but you can get the source from jQuery if you don't want to incorporate the entire library.
You can make use of javascript object oriented concept
Each table has its corresponding table object, so does its rows and cells.
With this technique, every object has its "element" in the real DOM.
The trick is, attach the event listener (e.g. when user types something in the textbox) to the object, so that that event listener will only correspond to that specific cell, not messing up with other cells in other column, row, and tables.
Here is possible solution. Sorry for my jQuery heavy dependent. I am just not sure how to create element with document.createElement() (my bad knowledge), you can of course change them with pure javascript implementation (no jQuery).
values=new Array();
function Cell(id,values_row){ //Cell class
this.id=id;
this.element=$("<td></td>");
this.textbox=$("<input type='text' name='"+this.id+"' id='"+this.id+"'></input>");
values_row[id]="" //initiate default value == ""
//here is the trick
this.textbox.change(function(){ //you can use onchange if you dont like jQuery
values_row[id]=$(this).val();
//other tasks need to be done when user changes the value of a textbox (typing)
});
this.textbox.appendTo(this.element);
}
function Row(id,number_of_columns,values_table){ //Row class
this.id=id
this.element=$("<tr></tr>")
values_table[id]=new Array(); //make array "values" becomes 3D
for(var col =0;col<number_of_columns;col++){
var the_cell=new Cell(col,values_table[col]);
the_cell.element.appendTo(this.element);
}
}
function Table(id,number_of_columns){ //Table class
this.id=id
this.element=$("<table></table>")
values[id]=new Array(); //make array "values" becomes 2D
for(var row=0;row<4;row++){
var the_row=new Row(row,number_of_columns,values[id]);
the_row.element.appendTo(this.element)
}
}
// creating the tables
for(var t=0;t<number_of_tables_needed;t++){
the_table=new Table(t,number_of_column_for_this_table);
the_table.element.appendTo(table_container_element);
}
//do input some text into some cells then
alert(values)
The alert will display a 3D array containing the values of all cells indexed by table number, row number, and of course the column that points exactly to a cell. The default value for cell's value is ""
With this technique, you do not need find which the correct array element for a corresponding cell whose value just been inputted. Instead, attach the event listener prior to the element creation in DOM.This is an object oriented way / approach to the problem.
Rather than having O(n^3) algorithm complexity when you need to find the corresponding array cell each time user makes an input, this solution is a taking a bit more time during object initialization, but afterwards, it is O(1).

Categories

Resources