Add new Row before first row in java script - javascript

Hi I have code as follows:
function addRowToTable(num){
if (hasLoaded) {
var tbl = document.getElementById(TABLE_NAME);
var nextRow = tbl.tBodies[0].rows.length;
var iteration = nextRow + ROW_BASE;
if (num == null) {
num = nextRow;
} else {
iteration = num + ROW_BASE;
}
// add the row
var row = tbl.tBodies[0].insertRow(num);
// cell
var cell0 = row.insertCell(0);
var LNInpT = document.createElement('input');
LNInpT.setAttribute('type', 'text');
LNInpT.setAttribute('value', 'name');
cell0.appendChild(LNInpT);
// Pass in the elements you want to reference later
// Store the myRow object in each row
row.myRow = new myRowObject(textNode, txtInp, cbEl, raEl);
}}
Please help me to Add new Row before first row in table with editing this code.
tanks

This should help you:
var myTable = document.getElementById('myTable');
var tbody = myTable.tbodies[0];
var tr = tbody.insertRow(-1); // puts it at the start
var td = document.createElement('td');
td.innerHTML = "Something";
tr.appendChild(td);

I'd recommend you use jQuery which will make this much easier (with the prepend method). If you can't or don't want to, you should be able to use insertBefore.
You might want to look at this question on SO.

Use jQuery's prepend() method for that.

Related

Add links to all cells in column of html table

I would like to loop through the cells in the second column of an html table, adding a link to the text in each cell. I have a generic base URL, with a hash that should be defined by an integer in the corresponding cell in the first column of the table.
For example, the text in first cell of the second column should link to:
http://test.example.com/foo.html#1
Where the #1 is defined by the integer in the first cell of the first column (1). Then repeat for each row, where the integer in each cell of the first column should be used for the hash.
Pure js or jquery would work. I have found this snippet of jquery, which seems like a good start for iterating through each cell in the second column:
$('#table1 td:nth-child(2)').each(function(elem) {
//do something with elem
});
Is this jquery method appropriate, and if so, how can I apply the links as described?
As a possible alternative, could I modify the function I use to create the table?:
function createTable(tableData) {
var table = document.getElementById('table1');
var tableBody = document.createElement('tbody');
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.getElementById('wrapper').appendChild(table);
}
createTable(table_input);
Since you are the one creating the table at the first place it is best to modify the code and render it correctly (as oppose to updating it later on client-side).
Based on your comments and clarification here is the updated code, storing the integer value of first column of each row to use it as url on second column:
function createTable(tableData) {
var table = document.getElementById('table1');
var tableBody = document.createElement('tbody');
var theUrl = 'http://test.example.com/foo.html#'; //replace with real URL
tableData.forEach(function(rowData) {
var row = document.createElement('tr');
var i = 1;
var numValue = '';
var content = '';
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
numValue = (i==1) ? cellData : numValue ;
if(i==2){
content = document.createElement('a');
content.setAttribute('href', theUrl + numValue);
content.innerText = cellData ;
}
else{
content = document.createTextNode(cellData);
}
cell.appendChild(content);
row.appendChild(cell);
i++;
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.getElementById('wrapper').appendChild(table);
}
createTable(table_input);
You may change the following code:
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
to
for (var i=0; i<rowData.length;i++)
{
var cell = document.createElement('td');
if (i==1)
{
var link=document.createElement("a");
link.href="http://test.example.com/foo.html#"+(i+1);
link.text=rowData[i];
cell.appendChild(link);
}
else
cell.textContent=rowData[i];
row.appendChild(cell);
}

HTML Table Row Creation

EDIT: With significant help from others, I was able to work up a solution.
I'm taking data from a Google Spreadsheet and then attempting to render it as an HTML table in a WebApp.
I'd like the data to show up like
<tr>
<td>
<td>
<td>
exactly how it looks in a spreadsheet, with each value in a separate cell.
Big picture, I'd like to be able to do different things to each <td>, so I want to make sure I structure the data in a usable way.
Code.GS
function doGet() {
return HtmlService.createHtmlOutputFromFile('Index');
}
function webAppTest() {
getTeamArray();
}
function getTeamArray() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange('A2:H1000');
var values = range.getValues();
//Logger.log(values);
var teamsArray = [];
for (var i = 0; i < values.length; ++i) {
var column = values[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
var colE = column[4];
var colF = column[5];
var colG = column[6];
var colH = column[7];
if (colA != '') {
teamsArray.push(values[i][0]);
teamsArray.push(values[i][3]);
teamsArray.push(values[i][4]);
}
}
var array2 = [];
while(teamsArray.length) array2.push(teamsArray.splice(0,3));
var lengthDivName2 = array2.length;
var widthDivName2 = array2[0].length;
//Logger.log(teamsArray);
Logger.log(array2);
//return teamsArray;
return array2;
}
Index.HTML Function
function buildOptionsList(teamsArray) {
var div = document.getElementById('myList');
for (var i = 0; i < teamsArray.length; i++) {
var tr = document.createElement('tr');
var td = document.createElement('td');
var cLass = td.setAttribute('class','ui-state-default');
var iD = td.setAttribute('id',teamsArray[i]);
td.appendChild(document.createTextNode(teamsArray[i]));
div.appendChild(tr);
div.appendChild(td);
}
}
</script>
</head>
<body>
<div id="myList" class="connectedSortable">MY LIST</div>
</body>
</html>
ATTEMPT 1
ATTEMPT 2
I tried to change the array creation in code.gs which got all the correct data in the <tr> but didn't split into <td>s
I am not sure I understood the way you receive the data, but if teamsArray contain information about one line the solution would be something like this:
function buildOptionsList(teamsArray) {
var div = document.getElementById('myList');
var tr = document.createElement('tr');
for (var i = 0; i < teamsArray.length; i++) {
var td = document.createElement('td');
var cLass = td.setAttribute('class','ui-state-default');
var iD = td.setAttribute('id',teamsArray[i]);
td.appendChild(document.createTextNode(teamsArray[i]));
tr.appendChild(td);
}
div.appendChild(tr);
}
Use Array#map, Array#reduce, and Array#join to surround the elements of the inner array with the required HTML tags and then condense to a single string. Currently you have an implicit Array#toString call which creates a comma-separated string of the inner array's elements (the inner array is at teamData[i]), and thus you only have a single cell in your previous attempts' output.
This simple function assumes you aren't applying any column- or row-specific styles or attributes, so it can simply treat every <td> element equivalently. If you have symmetric styling to apply, you would want to process the headers/row variables with .map first (since you can then use the elements' indices) and then .join("") instead of just .join using the tag delimiters.
function getTableHTMLFrom(array, hasHeaders) {
if (!array || !array.length || !array[0].length)
return "";
const headerString = (hasHeaders ?
"<tr><th>" + array.shift().join("</th><th>") + "</th></tr>"
: "");
const tdTag = "<td class=\"ui-state-default\">";
const bodyString = array.reduce(function (s, row) {
s += "<tr>" + tdTag + row.join("</td>" + tdTag) + "</td></tr>";
return s;
}, "");
return "<table>" + headerString + bodyString + "</table>";
}
I found a solution (applied to Index.HTML) that worked based on THIS.
function buildOptionsList(array2) {
var table = document.createElement('table');
var tableBody = document.createElement('tbody');
array2.forEach(function(rowData) {
var row = document.createElement('tr');
rowData.forEach(function(cellData) {
var cell = document.createElement('td');
var cLass = td.setAttribute('class','ui-state-default');
cell.appendChild(document.createTextNode(cellData));
row.appendChild(cell);
});
tableBody.appendChild(row);
});
table.appendChild(tableBody);
document.body.appendChild(table);
}
buildOptionsList(array2);

Fetching user input from input field into js table that creates table cells via for loop

I've been attempting to fetch user input value from input fields to later on set it into a summary table that creates cells using javascript but can't seem to get it to work.
Following is my code:
function summonTable(f) {
var sLoc = f.countryf.value();
var eLoc = f.countryt.value();
var sDate = f.sdate.value();
var eDate = f.edate.value();
var div = document.getElementById("summary");
var magicTable = document.getElementById('summaryTable').querySelectorAll('tbody tr'),
var row = document.createElement('tr');
var th = document.createElement('th');
th.textContent = sDate;
var td = document.createElement('td');
td.textContent = sLoc;
//To state which row and column this cell goes to.
row.appendChild(th);
div.appendChild(magicTable);
});
The function summonTable will take in the arguement form f that contains the input fields, I've tried basic textboxes, checkboxes, radios, but all to no avail. The variables sLoc, eLoc are basically texts for countries and sDate, eDate are supposed to be dates.
function summonTable(f) {
var sLoc = f.countryf.value();
var eLoc = f.countryt.value();
var sDate = f.sdate.value();
var eDate = f.edate.value();
var div = document.getElementById("summary");
// to get the last row of the table
var magicTable = document.getElementById('summaryTable').querySelectorAll('tbody tr:last-child'),
var row = document.createElement('tr');
var th = document.createElement('th');
th.textContent = sDate;
var td = document.createElement('td');
td.textContent = sLoc;
//To state which row and column this cell goes to.
row.appendChild(th);
magicTable.after(row); //To add the row after the last row
div.appendChild(magicTable);
});

how to insert a <td> to a <tr> using jquery

I have a table with few rows, I just need to re arrange them, I am able to fetch <td> and <tr> and now what I need to do is to insert them back in a custom order
$('.white-header').each(function() { //white-header is the class used for <tr>
var tr = $(this);
var td1 = tr.find('td:eq(4)'); // indices are zero-based here
var td2 = tr.find('td:eq(5)');
var td3 = tr.find('td:eq(6)');
var td4 = tr.find('td:eq(7)');
var td5 = tr.find('td:eq(8)');
var td6 = tr.find('td:eq(9)');
var td7 = tr.find('td:eq(10)');
td1.remove();
td2.remove();
td3.remove();
td4.remove();
td5.remove();
td6.remove();
td7.remove();
tr.insert(td7); // here am getting errors, i tried .append also
tr.insert(td6);
tr.insert(td4);
});
i just need to know how to insert td to this tr (currently tr is blank i guess, after removing all td)
You do not need .remove() at all. All you need is to use append and prepend (or appendTo and prependTo) in a clever way to rearrange your cells. These methods do not copy DOM nodes, they move them, so removal is completely unnecessary.
Quick example:
$('.white-header').each(function() {
var tr = $(this);
tr.find('td:eq(4)').appendTo(tr);
tr.find('td:eq(6)').appendTo(tr);
tr.find('td:eq(9)').prependTo(tr);
});
(in my example the order of the elements might seem strange at the end, because I don't run :eq on the original order, but always on the already changed order - this is only a quick example)
You are trying to append the deleted objects, You need to make clone of <td> and remove the <td> objects you have later append the cloned objects of insert
$('.white-header').each(function() { //white-header is the class used for <tr>
var tr = $(this);
var td1 = tr.find('td:eq(4)'); // indices are zero-based here
var td2 = tr.find('td:eq(5)');
var td3 = tr.find('td:eq(6)');
var td4 = tr.find('td:eq(7)');
var td5 = tr.find('td:eq(8)');
var td6 = tr.find('td:eq(9)');
var td7 = tr.find('td:eq(10)');
td1.remove();
td2.remove();
td3.remove();
td4Cloned = td4.clone();
td4.remove();
td5.remove();
td6Cloned = td6.clone();
td6.remove();
td7Cloned = td7.clone();
td7.remove();
tr.insert(td7Cloned); // here am getting errors, i tried .append also
tr.insert(td6Cloned);
tr.insert(td4Cloned);
});
Try using .detach()
$('.white-header').each(function() { //white-header is the class used for <tr>
var tr = $(this);
var td1 = tr.find('td:eq(4)').detach(); // indices are zero-based here
var td2 = tr.find('td:eq(5)');
var td3 = tr.find('td:eq(6)').detach();
var td4 = tr.find('td:eq(7)').detach();
var td5 = tr.find('td:eq(8)');
var td6 = tr.find('td:eq(9)');
var td7 = tr.find('td:eq(10)');
td1.remove();
td2.remove();
td3.remove();
td5.remove();
tr.append(td7); // here am getting errors, i tried .append also
tr.append(td6);
tr.append(td4);
});

How to add an UpperCase function to each textbox in a dynamic table?

I am trying to create a dynamic table with textboxes but I want the textboxes to be converted to upper case every time I write.
Any ideas on how to do this??
Currently this is how I am doing the dynamic table:
var n = 1;
function addRow(tableID,nroColumna) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
for(i=0;i<nroColumna;i++){
var cell = row.insertCell(i);
var element = document.createElement("input");
element.type = "text";
element.name = n+"0"+i;
element.size = "12";
element.id = n+"0"+i;
//element.onkeyup = function(){alert()};
cell.appendChild(element);
}
n++;
}
I was trying to do a document.getElementById(element.id).value.toUpperCase() but I am getting an error with a null value for the element.id
Any help is greatly appreciated!
If you're ok with a non JavaScript solution, you could apply this CSS to your inputs:
text-transform: uppercase;
That would make the text uppercase from the beginning...
Darkajax's solution, works, you can target it to inputs within a table with a specific ID
with
#tableid input
{
text-transform: uppercase;
}
I tested your code with the onkeyup function activated:
var n = 1;
function addRow(tableID,nroColumna) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
for(i=0;i<nroColumna;i++){
var cell = row.insertCell(i);
var element = document.createElement("input");
element.type = "text";
element.name = n+"0"+i;
element.size = "12";
element.id = n+"0"+i;
element.onkeyup = function(){alert(element.id);};
cell.appendChild(element);
}
n++;
}
And that worked. However, it uses the last element.id computed for every call to the function... so, when I created one row of 3 cells, every time I typed into a cell, it would alert "102" regardless of which cell I typed in.
This is because the onkeyup function is dynamic. It is called on the keyup action - not set when the object is created. So it uses the element.id value that exists at the time of the action, not what it was when you passed it in the first time. I hope that makes sense.
I had this issue myself on a recent project. One solution is to create a separate function for the inner workings of the for loop as such:
var n = 1;
function createRow (n, i) {
var element = document.createElement("input");
element.type = "text";
element.name = n+"0"+i;
element.size = "12";
element.id = n+"0"+i;
element.onkeyup = function(){alert(element.id);};
return element;
}
function addRow(tableID,nroColumna) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
for(i=0;i<nroColumna;i++){
var cell = row.insertCell(i);
element = createRow(n, i);
cell.appendChild(element);
}
n++;
}
This code alerts the correct element.id value.
EDIT: you can change the onkeyup() line to read:
element.onkeyup = function(){document.getElementById(element.id).value = document.getElementById(element.id).value.toUpperCase();};
And it should work as you want it to.
with jQuery it will be like
$('.yourClass').val($(this).val().toUpperCase());
or
$('#yourId').css({'text-transform' : 'uppercase'})

Categories