How to insert new rows in some position in table - javascript

I have page with table.
In tbody I show data via angularjs. In thead I have same row as in tbody, but its empty, and when I filled input field and click somewhere (focus lost), one row adds to my table (thead). And I need to make some flag on filled row, as like - rowAdded = true, because without that I clicking on input of one row and rows adds. And one more problem is that rows adds to the end of table.
it's all works on this script:
var tbody = $('.table-timesheet thead');
tbody.on('blur', ':text', function () {
var tr = $(this).closest('tr'),
notEmpty = $(':text', tr).filter(function () {
return $.trim($(this).val()) != '';
}).length;
if (notEmpty) {
$('.note-input').css('width', '88%').css('float', 'left');
$('.timesheet-delete-button').css('display', 'block');
//tr.clone(true).appendTo(tbody).find(':text').val('');
insRow();
}
});
function deleteRow(row) {
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('table-body').deleteRow(i);
}
function insRow() {
var table = document.getElementById('table-body');
var newRow = table.rows[1].cloneNode(true);
var len = table.rows.length;
newRow.cells[0].innerHTML = len;
var inp1 = newRow.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = newRow.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
table.appendChild(newRow);
}
There is my example in plunker:
http://plnkr.co/edit/rcnwv0Ru8Hmy7Jrf9b1C?p=preview

Is this what you are looking for
function insRow(ind){
var table = document.getElementById('table-body');
var newRow = table.rows[1].cloneNode(true);
var len = table.rows.length;
newRow.cells[0].innerHTML = ind!==undefined ? ind : len;
if(ind!==undefined)
$(table).find('tr:eq('+ind+')').before(newRow);
else table.appendChild(newRow);
}
insRow(2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table-body">
<tbody>
<tr><td>1</td></tr>
<tr><td>2</td></tr>
<tr><td>3</td></tr>
</tbody>
</table>

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);
}
*/
}

Calculate a new AveValue in TableCell while adding new Columns using JavaScript-not JQuery

I have a <th> header row with a stated class, and one fixed row with a stated class. Both are contenteditable. I'm adding new rows and new columns. I want to calculate the AverageValue in the final cell. I have tried the code on a fixed number of rows and it works, but when I try it this way it is only taking in the number of columns, not the DATA inserted. It is also not recognizing the row DATA. I'm clearly missing a function?!
I'm at the stage where I need an extra pair of eyes.
JavaScript:
func = function() {
var table = document.getElementById("mytable");
var rows = table.rows;
for (var j = 1; j < rows.length; j++) {
var total = 0;
var cells = rows[j].cells;
for (var i = 2; i < (cells.length - 1); i++) {
var a = document.getElementById("mytable").rows[j].cells[i].innerHTML;
a = parseInt(a);
if (!isNaN(a)) {
total = total + a;
}
}
total = total / (cells.length - 3);
total = Math.round(total);
if (total < 40) {
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.backgroundColor = "red";
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.color = "white";
}
document.getElementById("mytable").rows[j].cells[cells.length - 1].innerHTML = total + "%";
}
}
addRow = function() {
var table = document.getElementById('mytable'); // table reference
var row = table.insertRow(table.rows.length); // append table row
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), "-");
}
}
createCell = function(cell, text, style) {
var div = document.createElement('div');
txt = document.createTextNode(text);
div.appendChild(txt); // append text node to the DIV
div.setAttribute("class", style); // set DIV class attribute
div.setAttribute("className", style);
div.setAttribute("contenteditable", true);
div.setAttribute('placeholder', '' - '');
cell.appendChild(div); // append DIV to the table cell
}
createCellCol = function(cell, text, style) {
var div = document.createElement('div');
txt = document.createTextNode(text);
div.appendChild(txt); // append text node to the DIV
div.setAttribute("class", style); // set DIV class attribute
div.setAttribute("className", style);
div.setAttribute("contenteditable", true);
div.setAttribute("placeholder", "-");
cell.appendChild(div); // append DIV to the table cell
}
addColumn = function() {
var table = document.getElementById("mytable"); // table reference
var rowNums = table.rows.length;
for (i = 0; i < rowNums; i++) {
if (i == 0) {
createCell(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-");
} else {
createCellCol(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-");
}
}
}
HTML:
<table class="tg" id="mytable">
<tr>
<th class="tg-s6z2" contenteditable="true">Student Name</th>
<th class="tg-s6z2" contenteditable="true">Student ID</th>
<th class="tg-s6z2" contenteditable="true">Assignment 1</th>
<th class="tg-s6z2" contenteditable="true">Final Grade</th>
</tr>
<tr>
<td class="tg-031e" contenteditable="true">Student1</td>
<td class="tg-031e" contenteditable="true">StudentNo</td>
<td class="tg-0ord" contenteditable="true"></td>
<td class="tg-0ord" contenteditable="true"></td>
</tr>
</table>
<button id="btnFinalGrade" class="btn btn-action" onClick="func();">Final Grade</button>
<button id="btnaddRow" class="btn btn-action" onclick="addRow();">AddRow</button>
<button id="btnaddColumn" class="btn btn-action" onclick="addColumn();">AddColumn</button>
You were adding a div to td element which was throwing error while executing this line document.getElementById("mytable").rows[j].cells[i].innerHTML
which returns a div element not the text you entered!
No need to add a div, Here is the updated code,
func = function () {
var table = document.getElementById("mytable");
var rows = table.rows;
for (var j = 1; j < rows.length; j++) {
var total = 0;
var cells = rows[j].cells;
for (var i = 2; i < (cells.length - 1); i++) {
var a = document.getElementById("mytable").rows[j].cells[i].innerHTML;
a = parseInt(a);
if (!isNaN(a)) {
total = total + a;
}
}
total = total / (cells.length - 3);
total = Math.round(total);
if (total < 40) {
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.backgroundColor = "red";
document.getElementById("mytable").rows[j].cells[cells.length - 1].style.color = "white";
}
document.getElementById("mytable").rows[j].cells[cells.length - 1].innerHTML = total + "%";
}
}
addRow = function () {
var table = document.getElementById('mytable'); // table reference
var row = table.insertRow(table.rows.length); // append table row
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), "-","tg-031e");
}
}
createCell = function (cell, text, style) {
var div = document.createElement('td');
txt = document.createTextNode(text);
cell.appendChild(txt); // append text node to the DIV
cell.setAttribute("class", style); // set DIV class attribute
cell.setAttribute("className", style);
cell.setAttribute("contenteditable", true);
cell.setAttribute('placeholder', '' - '');
//cell.appendChild(div); // append DIV to the table cell
}
createCellCol = function (cell, text, style) {
var div = document.createElement('td');
txt = document.createTextNode(text);
cell.appendChild(txt); // append text node to the DIV
cell.setAttribute("class", style); // set DIV class attribute
cell.setAttribute("className", style);
cell.setAttribute("contenteditable", true);
cell.setAttribute("placeholder", "-");
//cell.appendChild(div); // append DIV to the table cell
}
addColumn = function () {
var table = document.getElementById("mytable"); // table reference
var rowNums = table.rows.length;
for (i = 0; i < rowNums; i++) {
if (i == 0) {
createCell(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-","tg-031e");
} else {
createCellCol(table.rows[i].insertCell(table.rows[i].cells.length - 1), "-","tg-s6z2");
}
}
}

inserting row in the middle of a html table using 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++;
}
});

MineField with Js

I am trying to create a minefield game with javascript.
When I click on clear ro**w it gives "passed" but sometimes "died" too or clicking on **mined row gives sometimes "passed". It's supposed to give only "passed" with clear and "died" with mined row.
I can't figure out the reason..
Could you see it?
Here is my code so far:
var level = 9;
// create the table
var body = document.getElementsByTagName("body")[0];
var tbl = document.createElement("table");
tbl.setAttribute('id', 'myTable');
var tblBody = document.createElement("tbody");
//Create 2d table with mined/clear
for (var i = 1; i <= 10; i++) {
var row = document.createElement("tr");
document.write("<br/>");
for (var x = 1; x <= 10; x++) {
var j = Math.floor(Math.random() * 50);
if (j <= 15) {
j = "mined";
} else {
j = "clear";
}
var cell = document.createElement("td");
var cellText = document.createTextNode(j + "");
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
tbl.setAttribute("border", "1");
//Check which row is clicked
window.onload = addRowHandlers;
function addRowHandlers() {
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("td");
for (p = 0; p < rows.length; p++) {
var currentRow = table.rows[p];
var createClickHandler = function (row) {
return function () {
var cell = row.getElementsByTagName("td")[1];
var id = cell.innerHTML;
if (id == "mined") {
alert("Died");
} else {
alert("Passed!");
}
};
}
currentRow.onclick = createClickHandler(currentRow);
}
}
JSFiddle Here:
http://jsfiddle.net/blowsie/ykuyE/
Thanks in advance!
Its' this line, which causes the faulty behaviour: var cell = row.getElementsByTagName("td")[1]; Everytime a click is made, the [1] selects the 2nd cell of a column, no matter which cell was actually clicked.
I modified your fiddle: http://jsfiddle.net/ykuyE/1
The onclick handler is now applied to the individual cell directly, when the table is created.
cell.onclick = function() {
if (this.innerHTML == "mined") {
alert("Died");
} else {
alert("Passed!");
}
}

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