How to add row to the beginning of table using javascript - javascript

I clone a row and append it to the end of a table the following function add_record().
My question is how to append it to the beginning of the table.
I tried using
$("#main_table_id tbody").prepend(clone)
and
$("#main_table_id tbody").prepend(clone.innerHtml)
but it didn't work.
function add_record(){
var row = document.getElementById("template_no_1_id");
var table = document.getElementById("main_table_id");
var clone = row.cloneNode(true);
clone.id = "newID";
table.appendChild(clone);
}

Use native function insertRow.
<table id="TableA">
<tr>
<td>Old top row</td>
</tr>
</table>
<script type="text/javascript">
function addRow(tableID) {
// Get a reference to the table
var tableRef = document.getElementById(tableID);
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(0);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createTextNode('New top row');
newCell.appendChild(newText);
}
// Call addRow() with the ID of a table
addRow('TableA');
</script>
Credit: https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement.insertRow

Related

JQuery Multiple Append Only Appends Last one [duplicate]

This question already has answers here:
Why do multiple `.appendTo` calls on a newly created jQuery element only append it once?
(2 answers)
Closed 3 months ago.
I want to use jQuery to create a table. Currently I have an empty table body and I would like to use some jQuery to fill up the table:
var $tr = $("<tr>"),
$td = $("<td>");
var date = '2018-01-01'
$td.text(date);
$tr.append($td);
$td.text("New Years");
$tr.append($td);
$("#body").append($tr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id='body'>
</tbody>
<table>
But this only appends the second td. The first one gets overwritten. Any ideas on how to fix?
Like Taplar said in comments, if the element already is in DOM, the .append will only "move it".
Now in your example, you append it a the same place, but also change the text.
Try the .clone() method to duplicate elements.
var $tr = $("<tr>");
var $td = $("<td>");
var date = '2018-01-01';
$td.text(date);
$tr.append($td);
var secondCell = $td.clone().text("New Years");
$tr.append(secondCell);
$("#body").append($tr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id='body'>
</tbody>
</table>
var $tr1 = $("<tr>"),
$tr2 = $("<tr>"),
$tr3 = $("<tr>"),
$td = $("<td>");
var date = '2018-01-01';
$td.text(date);
//various ways to accomplish it
$tr1.append($td.prop('outerHTML'));
$tr2.append($td.clone());
$tr3.append($('<td>', { text: date }));
$td.text("New Years");
$tr1.append($td.prop('outerHTML'));
$tr2.append($td.clone());
$tr3.append($('<td>', { text: 'New Years' }));
$("#body").append([$tr1, $tr2, $tr3]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id='body'>
</tbody>
<table>
You have to clone $td, so that DOM treats it as a new element.
var $tr = $("<tr>"),
$td = $("<td>");
var date = '2018-01-01'
$td.text(date);
$tr.append($td.clone());
$td.text("New Years");
$tr.append($td.clone());
$("#body").append($tr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id='body'>
</tbody>
<table>
You can try next code without jquery:
let tbody = document.querySelector('#body');
let tr = document.createElement('tr');
let td = document.createElement('tr');
td.textContent = '2018-01-01';;
let tdClone = td.cloneNode();
tdClone.textContent = "New Years";
tr.append(td,tdClone);
tbody.append(tr);
I think that is true way, because you can create new td instead of clone created td (maybe for example this td has special classes or atributes), and you code repaint DOM only after insert tr in table.
Hmm... Maybe this could be an alternative to do that:
var texts = ["2018-01-01", "New Years"];
$.each(texts, function(i, val){
$("<tr><td>"+val+"</td></tr>").appendTo("#body")
});
$.each gets each item on the array texts, wrap it on tr and td, then append to the result on #body.
working fiddle

Table content replaced with new one in JavaScript

If I click on the submit button, then insert new cell, and click more than one time cells inserts again and again in a table i want to only add items only one time in table not again and again.
i want to call clear previous data and add new one when call fillTable().
my code is below here
<html>
<body>
<input type="button" onclick="fillTable()" value="submit">
<div id="out" >
<h2>Results are</h2>
<table id="tblData" border="1">
<tr>
<th>Name</th>
<th>Share</th>
</tr>
</table>
</div>
<script>
function fillTable(){
clearCells(); // clear previous
var tableRef = document.getElementById("tblData");
var rowcount = tableRef.rows.length;
var newRow = tableRef.insertRow(rowcount);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newText1 = document.createTextNode("Hello");
var newText2 = document.createTextNode("12000");
newCell.appendChild(newText1);
newCell2.appendChild(newText2);
newCell.appendChild(newText1);
newCell2.appendChild(newText2);
}
function clearCells(){
var tableRef = document.getElementById("tblData");
tableRef.deleteCell(0);
tableRef.deleteCell(1);
}
</script>
</body>
</html>
your problem was in your clearCell method, I fixed it for you:
function clearCells(){
var tableRef = document.getElementById("tblData");
if(tableRef.rows.length > 1){
tableRef.deleteRow(1);
}
}

Trouble with setting id for dynamically generated table

Never mind. This was my mistake. This code works fine.
I have a function that's supposed to create and populate a table. I'm also trying to set the id element of some of the columns, but the function that I have isn't working and I can't seem to figure out why.
This is my code:
HTML:
<div id="result_table">
<table border="0" cellspacing="3" cellpadding="3" id="summaryTable" class="tablesorter table table-striped">
<thead>
<tr style="font-weight: bold; text-align: center;">
<th>Well ID</th>
<th>Dominant Gene</th>
<th>%</th>
<th>Secondary Gene</th>
<th>%</th>
<th>No. of Reads that Mapped</th>
<th>No. of Mutations</th>
<th>Mutation Information</th>
<th>View</th>
</tr>
</thead>
<tbody id="summaryBody">
</tbody>
</table>
</div>
Javascript:
function structureTable(test){
if (kiloseqResult==null){
throw "Error: no databse defined"
};
document.getElementById("summaryTable").style.visibility="visible";
kiloseqDatabase = JSON.parse(kiloseqResult);
var table = document.getElementById("summaryBody");
for (i=0;i<kiloseqDatabase.length;i++){
var row = table.insertRow(i);
var kiloseqKeys = Object.keys(kiloseqDatabase[i])
var keyLength = Object.keys(kiloseqDatabase[i]).length;
// Painstakingly setting up the cells...
var cell = row.insertCell(0);
cell.innerHTML = kiloseqDatabase[i]['id']
var cell = row.insertCell(1);
cell.innerHTML = kiloseqDatabase[i]['gene1'].substr(5)
var cell = row.insertCell(2);
cell.innerHTML = parseFloat(kiloseqDatabase[i]['percent1']).toFixed(2)
var cell = row.insertCell(3);
if (kiloseqDatabase[i]['gene2']=="None"){
cell.innerHTML = "None"
} else {
cell.innerHTML = kiloseqDatabase[i]['gene2'].substr(5)
}
var cell = row.insertCell(4);
cell.innerHTML = parseFloat(kiloseqDatabase[i]['percent2']).toFixed(2)
var cell = row.insertCell(5);
cell.innerHTML = kiloseqDatabase[i]['count']
var cell = row.insertCell(6);
cell.innerHTML = ""
var cell = row.insertCell(7);
cell.innerHTML = ""
var cell = row.insertCell(8);
cell.innerHTML = ""
};
$(document).ready(function()
{
$("#summaryTable").tablesorter(
{sortList: [[0,0], [1,0]]}
);
}
);
for (i=0;i<kiloseqDatabase.length;i++){
document.getElementById("summaryBody").rows[i].cells[6].id = "test";
};
};
kiloseqResult is a variable that checks whether kiloseqDatabase is populated. kiloseqDatabase contains the information that's supposed to populate the table.
Oddly enough, the for-loop that sets up the ID (and yes, I did try including this in the first for-loop but tried breaking it up when that didn't work) is fine when I run it in my Chrome's console. But it doesn't seem to work within the function.
Any help would be much appreciated. Thank you!
Have you tried putting your ID assignment logic within the document.ready scope? You can't assign an ID to an element or select it from the DOM before it's rendered:
$(document).ready(function()
{
$("#summaryTable").tablesorter(
{sortList: [[0,0], [1,0]]}
);
for (i=0;i<kiloseqDatabase.length;i++){
document.getElementById("summaryBody").rows[i].cells[6].id = "test";
};
}
);

Insert row after row Javascript

I'm not so good at Javascript and can't get one thing working.
I have a table, something like this:
<table>
<tr><td>test #1</td><td>Here we go1!</td></tr>
<tr><td>test #2</td><td>Here we go2!</td></tr>
<tr><td>test #3</td><td>Here we go3!</td></tr>
</table>
And I need to insert new row with some content (not clone) after row with pressed link.
So in other words, after pressing on <a> in first row, the table have to be like this:
<table>
<tr><td>test #1</td><td>Here we go1!</td></tr>
<tr><td>some content here</td><td>some content here</td></tr>
<tr><td>test #2</td><td>Here we go2!</td></tr>
<tr><td>test #3</td><td>Here we go3!</td></tr>
</table>
I really tried to do something but it was always inserting before of after table.
UPDATE:
My JS code to insert new row looks something like this:
(I tried to use one solution posted here but it doesn't work).
function RowAdd()
{
var table=document.getElementById("test");
var last=$(this).closest("tr").prevAll().length;
var row=table.insertRow(last);
row.insertCell(0);
row.cells[0].innerHTML="test";
row.insertCell(1);
row.cells[1].innerHTML="test";
row.insertCell(2);
row.cells[2].innerHTML="test";
}
If I understand you need to do that, right ?
http://jsfiddle.net/OxyDesign/v7swo505/
JS (with jQuery)
$(document).ready(function(){
$('body').on('click','table a', function(e){
$(this).closest('tr').after('<tr><td>New Content 1</td><td>New Content 2</td></tr>');
});
});
Assuming your table has an id=myTable, you can use:
var table = document.getElementById("myTable");
var row = table.insertRow(1); //inserts row at index 1, like in your example
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "data1";
cell2.innerHTML = "data2";
This will work with other examples or deleting them too.
<body>
<table id="myTable">
<tr><td>test #1</td><td>Here we go1!</td></tr>
<tr><td>test #2</td><td>Here we go2!</td></tr>
<tr><td>test #3</td><td>Here we go3!</td></tr>
<tr><td>test #4</td><td>Here we go4!</td></tr>
<tr><td>test #5</td><td>Here we go5!</td></tr>
</table>
</body>
<script>
var table = document.getElementById("myTable");
var row = table.insertRow(1); //inserts row at index 1, like in your example
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "data1";
cell2.innerHTML = "data2";
// This line becomes the 4th line after the insert.
// But it has the row value of 3, because row 1 is 0
// <tr><td>test #3</td><td>Here we go3!</td></tr>
var row = table.deleteRow(3); //inserts row at index 1, like in the example
</script>
https://jsfiddle.net/vr_driver/zjaoqbyh/7/

Add table row before or after a table row of known ID

In a table like this:
<table>
<!-- Insert Row of bun here -->
<tr id="meat">
<td>Hamburger</td>
</tr>
<!-- Insert Row of bun here -->
</table>
function AddBefore(rowId){}
function AddAfter(rowId){}
I need to create methods without using jQuery.. I am familiar with append after and append before in jQuery.. but I am stuck with using plain js.
Use
function AddBefore(rowId){
var target = document.getElementById(rowId);
var newElement = document.createElement('tr');
target.parentNode.insertBefore(newElement, target);
return newElement;
}
function AddAfter(rowId){
var target = document.getElementById(rowId);
var newElement = document.createElement('tr');
target.parentNode.insertBefore(newElement, target.nextSibling );
return newElement;
}
You want insertBefore. Use with nextSibling to insert after a known element.

Categories