inserting row in the middle of a html table using javascript - javascript

I have a table which contains two rows.
<tr id="row1"><td>first row</td></tr>
<tr id="row2"><td>second row</td></tr>
I need to insert few rows between row1 and row2 using java script.
I can achieve this by using java script create element. But I wish to add new rows using string html content.
for example :
"<tr><td>This row is placed between first and second</td></tr>".insertAfter(first row Id);
is there way like this to add rows in between?

var newRow = document.createElement("tr");
newRow.innerHTML = "<td>This row is placed... etc.</td>";
var row2 = document.getElementById("row2");
row2.parentNode.insertBefore(newRow, row2);
Read up on it here: https://developer.mozilla.org/en-US/docs/Web/API/Node.insertBefore

Use jQuery. There is a Function insertAfter();
$("#row1").insertAfter("your html");
http://jquery.com/

var button = document.getElementById('insert');
var table = document.getElementById('table');
button.onclick = function() {
var position=Math.round(table.rows.length / 2);
var row = table.insertRow(position);
row.innerHTML = '<td>This row is placed between '+position+' and '+(parseInt(position)+1)+'</td>';
}
**after that if u can use like that u can increment ur row id also:**
var rowId = '#' + tableId + ' tr';
var k = 0;
$(rowId).each(function () {
var ObjInput = $(this).find('input[type=text],input[type=radio],input[type=checkbox],textarea,select,input[type=img],input[type=hidden],input[type=button],img');
if (ObjInput != null) {
for (var j = 0; j < ObjInput.length; j++) {
var inputId = $(ObjInput[j]).attr('id');
inputId = inputId.replace(/_[0-9]{1,2}/g, '_' + k);
$(ObjInput[j]).attr('id', inputId);
$(ObjInput[j]).attr('name', inputId);
}
k++;
}
});

Related

How to dynamically add <a> in a html table?

I have a table generated from an array. I'm looking to add a hyperlink to the entire first column of the <tbody> and only the first column.
I am able to add the <a> after the table is created, but then it doesn't actually contain the url within it, it simply appends to what already exists.
Specifically, how can I add a hyperlink to the first column of the
<tbody>?
Generally, as the table is being made, how can I specify different
things (anchors, classes, styles, etc.) for different columns?
http://jsfiddle.net/nateomardavis/n357gqo9/10/
$(function() {
google.script.run.withSuccessHandler(buildTable)
.table();
});
//TABLE MADE USING for
function buildTable(tableArray) {
var table = document.getElementById('table');
var tableBody = document.createElement('tbody');
var tbodyID = tableBody.setAttribute('id', 'tbody');
for (var i = 0; i < tableArray.length; ++i) {
var column = tableArray[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
if (colA != "") {
var row = document.createElement('tr');
var getTbody = document.getElementById('tbody');
for (var j = 0; j < column.length; ++j) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(column[j]));
row.appendChild(cell);
//NEXT TWO LINES DO NOT WORK
var firstCol = getTbody.rows[i].cells[0];
firstCol.setAttribute('class', 'TEST');
}
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
document.body.appendChild(table);
/* WORKS AFTER TABLE IS CREATED BUT CAN'T CAPUTRE INTERNAL LINK
var getTbody = document.getElementById('tbody');
for (var i = 0; i < getTbody.rows.length; i++) {
var firstCol = getTbody.rows[i].cells[0]; //first column
//firstCol.style.color = 'red';
//firstCol.setAttribute('class', 'TEST');
var link = document.createElement('a');
firstCol.appendChild(link);
}
*/
}

How to find out which row was clicked?

Hello i generate a Table with javascript and now i wont to find out which row and column the user has clicked?
Here are my function for the table:
function doNextSteps() {
removeAustriaFromCountries();
//insert table
var table = document.createElement("table");
table.setAttribute('id', 'matrixTable');
table.setAttribute('class', 'jbiTable');
// insert MATRIX row
var matrixRow = table.insertRow();
var cell = matrixRow.insertCell(); // left column for countries
cell.setAttribute('class', 'jbiMatrixCell');
cell.setAttribute('colSpan', departments.length + 1);
cell.appendChild(document.createTextNode("MATRIX"));
// insert departments row
var departmentsRow = table.insertRow();
var cell = departmentsRow.insertCell(); // left column for countries
cell.setAttribute('class', 'jbiBlankCell');
for (var i = 0; i < departments.length; i++) {
var cell = departmentsRow.insertCell();
cell.appendChild(document.createTextNode(departments[i].name));
cell.setAttribute('class', 'jbiDepartmentCell');
}
for (var i = 0; i < countries.length; i++) {
var countryRow = table.insertRow();
var cell = countryRow.insertCell(); // left country column
//cell.appendChild(document.createTextNode(countries[i].name));
var img = document.createElement('img');
img.src = "example.com + flags[i].name";
cell.appendChild(img);
cell.setAttribute('class', 'jbiCountryCell');
for (var j = 0; j < departments.length; j++) {
var cell = countryRow.insertCell();
var img = document.createElement('img');
img.src = "https://intranet.windkraft.at/OrganisationManual/Documents/Kreis.jpg";
img.onclick = function () {
window.location.href = "example.com" + pdfFiles[i].name;
};
cell.appendChild(img);
cell.setAttribute('class', 'jbiCircleCell');
}
}
$("#divTable").append(table);
}
The table gets generated and now i want to know in which header and in which column the user has clicked. With that information i want to make a new query to get files dynamically displayed in the Table. Any help would be great. And thanks for your Help.
To get the index of the row, you can use this code in your event listener function:
function onClick() {
var cell = this;
var row = cell.parentNode;
var cellIndex = Array.prototype.indexOf.call(row.children, cell);
var rowIndex = Array.prototype.indexOf.call(row.parentNode.children, row);
// do stuff with rowIndex, cellIndex
// rowIndex is the row number starting with row 0
// cellIndex is the column number starting with column 0
}
You can use parentNode.rowIndex & cellIndex to get the cell & rowIndex
document.getElementsByTagName('table')[0].addEventListener('click', function(e) {
console.log(e.target.parentNode.rowIndex,' ',e.target.cellIndex);
}, false);
Check this jsFiddle

jQuery Add row to table with dynamic ids'

http://jsfiddle.net/waH5S/6/
function add_row_retail() {
$(document).ready(function () {
var table = document.getElementById("Retail");
var row = table.insertRow(-1);
var row_id = $('#Retail').val('tr[id]:last');
console.log(row_id);
var cell_init = row.insertCell(-1);
cell_init.innerHTML = "blank";
});
}
I am trying to get the id of the table row(<tr>) before the added row, and then add 1 to this, with proper parseint(...). Then doing the same with the cell (<td>) next, so that every cell has a unique id for each table. I can't seem to find the row's id.
HERE IS THE "CORRECT" CODE FOR MY QUESTION
function add_row_retail() {
var table = document.getElementById("Retail");
// Row id
var row_id = $('#Retail tr:last').attr('id');
var row = table.insertRow(-1);
var next_row_id = "tr_" + (1+parseInt(row_id.match(/\d+/)[0],10));
$(row).attr('id', next_row_id);
for (var i = 0; i < 8; i++) {
var cell_id = $('#Retail td:last').attr('id');
console.log(cell_id);
var next_cell_id = "td_" + (1+parseInt(cell_id.match(/\d+/)[0],10)); console.log(next_cell_id);
var cell = row.insertCell(-1);
$(cell).attr('id', next_cell_id);
$(cell).innerHTML = "blank";
}
}
Rather than $('#Retail').val('tr[id]:last'); I think you want:
var row_id = $('#Retail tr:last').attr('id')
This selector finds the last tr under the #Retail element, and returns its id attribute.
jQuery last selector: http://api.jquery.com/last-selector/
Next problem: IDs cannot start with numbers. Rename your IDs like "tr_1", "tr_2", etc.
Next problem: To extract the numbers from a string:
"tr_123".match(/\d+/)[0]; // returns 123.
Add 1 to it:
var next_id = "tr_" + (1+parseInt("tr_123".match(/\d+/)[0],10));
Then, set your new id.
var row = table.insertRow(-1);
...
$(row).attr('id', next_id);

Create html table from comma separated strings javascript

I am trying to write a Javascript function which writes the text to (eventually) create the following html tables (I will be passing different length arguments to it to create hundreds of tables):
<table>
<tr><td><u>School</u></td>
<td><u>Percent</u></td>
<tr><td>School 1: </td>
<td>Percent1</td></tr>
<tr><td>School 2: </td>
<td>Percent2</td></tr>
<tr><td>School 3: </td>
<td>Percent3</td></tr>
</table>
The inputs that I have are comma separated strings:
var school_list = "School 1, School 2, School 3"
var pct_list = "Percent1, Percent2, Percent3"
The function needs to be passed school_list and pct_list, and return a string of the html table code above.
Something like this:
var schoolArr = school_list.split(',');
var pctArr = pct_list.split(',');
var table = "<table>";
for (var i=0; i< schoolArr.length; i++) {
table = table + "<tr><td>"+ schoolArr[i]+"</td><td>"+ pctArr[i] +"</td></tr>";
}
table = table + "</table>";
return table;
You can try below code with Jsfiddle demo ::
function createTable(tab) {
var tar = document.getElementById(tab);
var table = document.createElement('TABLE');
table.border = '1';
var tbdy = document.createElement('TBODY');
table.appendChild(tbdy);
for (var j = 0; j < 4; j++) {
var tr = document.createElement('TR');
tbdy.appendChild(tr);
for (var k = 0; k < 2; k++) {
var td = document.createElement('TD');
td.width = '100';
if (k == 0) td.innerHTML = "School" + (j + 1);
else td.innerHTML = "Percent" + (j + 1);
tr.appendChild(td);
}
}
tar.appendChild(table);
}
createTable('tab');
<div id="tab"></div>
var schools = school_list.split(/,\s*/g).join('</td><td>');
var pcts = pct_list.split(/,\s*/g).join('</td><td>');
return '<table><tr><td>' + schools + '</td></tr><tr><td>' + pcts + '</td></tr></table>'
or a better approach is to construct the whole table in DOM and place it in document directly.
function appendTD(tr, content) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(content));
tr.appendChild(td);
}
var table = document.createElement('table');
school_list.split(/,\s*/g).forEach(appendTD.bind(null, table.appendChild(document.createElement('tr'))));
pct_list.split(/,\s*/g).forEach(appendTD.bind(null, table.appendChild(document.createElement('tr'))));
someParent.appendChild(table);
var numberOfSchools = school_list.split(',');
var numberOfPercent = pct_list.split(',');
var htmlOutput= '<table><tr><td><u>School</u></td><td><u>Percent</u></td>';
for(var i = 0 ; i < numberOfSchools.length; i++)
{
htmlOutput += "<tr><td>" + numberOfSchools[i] + "</td>";
htmlOutput += "<td>"+numberOfPercent[i] +"</td></tr>"
}
htmlOutput += "</table>"
And return htmlOutput
Here's a DOM method, highlighs why innerHTML is so popular. DOM methods are pretty fast in execution lately, but the amount of code is a bit tiresome unless there's a good reason to use it.
The amount of code can be significantly reduced with a couple of helper functions so it is on par with innerHTML methods:
var school_list = "School 1, School 2, School 3"
var pct_list = "Percent1, Percent2, Percent3"
function makeTable(schools, percents) {
// Turn input strings into arrays
var s = schools.split(',');
var p = percents.split(',');
// Setup DOM elements
var table = document.createElement('table');
var tbody = table.appendChild(document.createElement('tbody'));
var oRow = document.createElement('tr');
var row;
oRow.appendChild(document.createElement('td'));
oRow.appendChild(document.createElement('td'));
table.appendChild(tbody);
// Write header
row = tbody.appendChild(oRow.cloneNode(true));
row.childNodes[0].appendChild(document.createTextNode('School'));
row.childNodes[1].appendChild(document.createTextNode('Percent'));
// Write rest of table
for (var i=0, iLen=s.length; i<iLen; i++) {
row = tbody.appendChild(oRow.cloneNode(true));
row.childNodes[0].appendChild(document.createTextNode(s[i]));
row.childNodes[1].appendChild(document.createTextNode(p[i]));
}
document.body.appendChild(table);
}
It can be called after the load event, or just placed somewhere suitable in the document:
window.onload = function() {
makeTable(school_list, pct_list);
}

Adding an onclick event to a table row

I'm trying to add an onclick event to a table row through Javascript.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 1; i < rows.length; i++) {
row = table.rows[i];
row.onclick = function(){
var cell = this.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
}
}
This works as expected in Firefox, but in Internet Explorer (IE8) I can't access the table cells. I believe that is somehow related to the fact that "this" in the onclick function is identified as "Window" instead of "Table" (or something like that).
If I could access the the current row I could perform a getElementById in the onclick function by I can't find a way to do that. Any suggestions?
Something like this.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
EDIT
Working demo.
Simple way is generating code as bellow:
<!DOCTYPE html>
<html>
<head>
<style>
table, td {
border:1px solid black;
}
</style>
</head>
<body>
<p>Click on each tr element to alert its index position in the table:</p>
<table>
<tr onclick="myFunction(this)">
<td>Click to show rowIndex</td>
</tr>
<tr onclick="myFunction(this)">
<td>Click to show rowIndex</td>
</tr>
<tr onclick="myFunction(this)">
<td>Click to show rowIndex</td>
</tr>
</table>
<script>
function myFunction(x) {
alert("Row index is: " + x.rowIndex);
}
</script>
</body>
</html>
I think for IE you will need to use the srcElement property of the Event object. if jQuery is an option for you, you may want to consider using it - as it abstracts most browser differences for you. Example jQuery:
$("#tableId tr").click(function() {
alert($(this).children("td").html());
});
Here is a compact and a bit cleaner version of the same pure Javascript (not a jQuery) solution as discussed above by #redsquare and #SolutionYogi (re: adding onclick event handlers to all HTML table rows) that works in all major Web Browsers, including the latest IE11:
function addRowHandlers() {
var rows = document.getElementById("tableId").rows;
for (i = 0; i < rows.length; i++) {
rows[i].onclick = function(){ return function(){
var id = this.cells[0].innerHTML;
alert("id:" + id);
};}(rows[i]);
}
}
window.onload = addRowHandlers();
Working DEMO
Note: in order to make it work in IE8 as well, instead of this pointer use the explicit identifier like function(myrow) as suggested by #redsquare.
Best regards,
Head stuck in jq for too long. This will work.
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 1; i < rows.length; i++) {
var row = table.rows[i];
row.onclick = function(myrow){
return function() {
var cell = myrow.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
}(row);
}
}
Here is how I do this. I create a table with a thead and tbody tags.
And then add a click event to the tbody element by id.
<script>
document.getElementById("mytbody").click = clickfunc;
function clickfunc(e) {
// to find what td element has the data you are looking for
var tdele = e.target.parentNode.children[x].innerHTML;
// to find the row
var trele = e.target.parentNode;
}
</script>
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
</tr>
</thead>
<tbody id="mytbody">
<tr><td>Data Row</td><td>1</td></tr>
<tr><td>Data Row</td><td>2</td></tr>
<tr><td>Data Row</td><td>3</td></tr>
</tbody>
</table>
I try to figure out how to get a better result with pure JS and i get something this:
DEMO: https://jsfiddle.net/f5r3emjt/1/
const tbody = document.getElementById("tbody");
let rowSelected;
tbody.onclick = (e) => {
for (let i = 0; i < e.path.length; ++i) {
if (e.path[i].tagName == "TR") {
selectRow(e.path[i]);
break;
}
}
};
function selectRow(r) {
if (rowSelected !== undefined) rowSelected.style.backgroundColor = "white";
rowSelected = r;
rowSelected.style.backgroundColor = "dodgerblue";
}
And now you can use the variable rowSelected in other function like you want or call another function after set the style
I like more this implementacion and also compatible with any browser
tbody.onclick = (e) => {
// we need to get the tr element because we always select the td element
const tr = e.srcElement.parentNode;
tr == "TR" && selectRow( tr );
};
Try changing the this.getElementsByTagName("td")[0]) line to read row.getElementsByTagName("td")[0];. That should capture the row reference in a closure, and it should work as expected.
Edit: The above is wrong, since row is a global variable -- as others have said, allocate a new variable and then use THAT in the closure.
My table is in another iframe so i modified SolutionYogi answer to work with that:
<script type="text/javascript">
window.onload = addRowHandlers;
function addRowHandlers() {
var iframe = document.getElementById('myiframe');
var innerDoc = (iframe.contentDocument) ? iframe.contentDocument : iframe.contentWindow.document;
var table = innerDoc.getElementById("mytable");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
alert("id:" + id);
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
</script>
I was trying to select a table row, so that it can be easily copied to the clipboard and then pasted in Excel. Below is a small adaptation of your solution.
References:
Where I took the window.prompt line from (Jarek Milewski):
The user is presented with the prompt box, where the text to be copied is already selected...
For selecting a complete table (Tim Down). Very interesting, but I was not able to adapt for a <tr> element.
<!DOCTYPE html>
<html>
<body>
<div>
<table id="tableId" border=1>
<tbody>
<tr><td>Item <b>A1</b></td><td>Item <b>B1</b></td></tr>
<tr><td>Item <b>A2</b></td><td>Item <b>B2</b></td></tr>
<tr><td>Item <b>A3</b></td><td>Item <b>B3</b></td></tr>
</tbody>
</table>
</div>
<script>
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
var cell1 = row.getElementsByTagName("td")[1];
var id2 = cell1.innerHTML;
// alert(id + " - " + id2);
window.prompt("Copy to clipboard: Ctrl+C, Enter", "<table><tr><td>" + id + "</td><td>" + id2 + "</td></tr></table>")
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
window.onload = addRowHandlers();
</script>
</body>
</html>
While most answers are a copy of SolutionYogi's answer, they all miss an important check to see if 'cell' is not null which will return an error if clicking on the headers.
So, here is the answer with the check included:
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler = function(row) {
return function() {
var cell = row.getElementsByTagName("td")[0];
// check if not null
if(!cell) return; // no errors!
var id = cell.innerHTML;
alert("id:" + id);
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
selectRowToInput();
function selectRowToInput(){
var table = document.getElementById("table");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++)
{
var currentRow = table.rows[i];
currentRow.onclick = function() {
rows=this.rowIndex;
console.log(rows);
};
}
}

Categories

Resources