Trouble with setting id for dynamically generated table - javascript

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";
};
}
);

Related

Add new row at each HTML page load with Javascript [duplicate]

This question already has answers here:
How to make changes to HTML document permanent using Javascript?
(3 answers)
Closed 3 years ago.
I've got a really basic HTML page that simply displays a table. I'm trying the below code so that I can add a new row to the bottom of the table each time the page is loaded (even if it's the same data for now). However, each time I load the page, the bottom element keeps getting overridden with the same data. I am trying to do something like this example on W3 Schools (without the button, but the same concept).
My code is as follows:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="table" style="width:70%; text-align: center;">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Row</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
<script>
function myFunction() {
var table = document.getElementById("table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
};
myFunction();
</script>
</body>
</html>
I've also tried replacing myFunction above with document.addEventListener("DOMContentLoaded", function(){...}, but that hasn't solved my issue either.
JavaScript will not make permanent changes in your HTML files.
This means that after you load the page, your HTML code will be displayed and then the function will be executed, adding a new row.
After you reload again, the same process will happen, and the row will be added after the end of your second HTML row.
It doesn't matter whether you use the simple method on your code or the other one you suggest (with document.addEventListener), this function is bound to be executed only once and will not add more than one row.
The issue is that your page isn't storing its data anywhere, so whenever you reload the page you're basically destroying any data you've modified and loading it from scratch again. You should use localStorage or a local database or something like that to keep track of data, and save your page's state when the function is called or on page unload.
In pseudocode:
const loadFromLocalStorage = () => {
const rows = localStorage.getItem("extra_rows") // extra_rows can be an array
for(elem in rows) {
// add to table
}
}
const saveToLocalStorage = (obj) => {
const rows = localStorage.getItem("extra_rows")
localStorage.setItem([...rows, obj])
}
const addNewRow = () => {
var table = document.getElementById("table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
const obj = {
cell1: cell1, cell2: cell2, cell3: cell3
}
saveToLocalStorage(obj)
}
const myFunction = () => {
loadFromLocalStorage()
addNewRow()
}
myFunction()

Changing JavaScript code to jQuery of my own script

I need a help on changing the JavaScript code to jQuery of my own code.
TASK:
When I click the '+' button on the tree, it shows/adds a new row to the table also the button changes to '-'(minus). After that, again I click on the minus(-) button, it hides the row.
The above task is done in javascript. I need to convert it to jQuery. Is it possible? If yes means, please help me. Thanks in advance.
The code is as follows:
<html>
<head>
<title>Appending table row in a table</title>
<script language = "javascript">
function changeImage(that,x)
{
var clickedrow = document.getElementById("append"+x);
var subrow = document.getElementById("append"+x+"a");
var table = document.getElementById("mytable");
if(that.src === "http://renko-server/sample/arun/jquery/images/plus.gif")
{
that.src = "http://renko-server/sample/arun/jquery/images/minus.gif";
if(subrow)
{
subrow.style.display="";
}
else
{
subrow = table.insertRow(clickedrow.rowIndex+1);
subrow.id="append"+x+"a";
var cell1 = subrow.insertCell(0);
var cell2 = subrow.insertCell(1);
var cell3 = subrow.insertCell(2);
cell1.innerHTML = "";
cell2.innerHTML = "Kumar";
cell3.innerHTML = "Madurai";
}
}
else
{
that.src = "http://renko-server/sample/arun/jquery/images/plus.gif";
subrow.style.display="none";
}
}
</script>
</head>
<body>
<table id="mytable" class="appendtable">
<tr><td></td><td><b>Name</b></td><td><b>Location</b></td></tr>
<tr id="append1"><td><img id="plus1" onclick="javascript:changeImage(this,1);" src="http://renko-server/sample/arun/jquery/images/plus.gif" / ></td><td>Arun</td><td>Sivakasi</td></tr>
<tr id="append2"><td><img onclick="javascript:changeImage(this,2);" id="plus2" src="http://renko-server/sample/arun/jquery/images/plus.gif"/></td><td>Raj</td><td>Kovai</td></tr>
<tr id="append3"><td><img id="plus3" src="http://renko-server/sample/arun/jquery/images/plus.gif" onclick="javascript:changeImage(this,3);"/></td><td>Jerome</td><td>Bangalore</td></tr>
</table>
</body>
</html>
change you html like this:-
<table id="mytable" class="appendtable">
<tr><td></td><td><b>Name</b></td><td><b>Location</b></td></tr>
<tr id="append1"><td><img id="plus1" onclick="changeImage(this);" src="http://renko-server/sample/arun/jquery/images/plus.gif" /> ></td><td>Arun</td><td>Sivakasi</td></tr>
// ^^^ this is change
<tr id="append2"><td><img onclick="changeImage(this);" id="plus2" src="http://renko-server/sample/arun/jquery/images/plus.gif" /></td><td>Raj</td><td>Kovai</td></tr>
<tr id="append3"><td><img id="plus3" src="http://renko-server/sample/arun/jquery/images/plus.gif" onclick="javascript:changeImage(this);" /></td><td>Jerome</td><td>Bangalore</td></tr>
</table>
and your jquery function is:-
function changeImage(that) {
var clickedrow = $(that);
var subrow = $('#' + clickedrow.attr('id') + 'a');
var table = $("#mytable");
if (clickedrow.attr('src') === "http://renko-server/sample/arun/jquery/images/plus.gif") {
clickedrow.attr('src', "http://renko-server/sample/arun/jquery/images/minus.gif");
if (subrow.length) {
subrow.show();
}
else {
subrow = $('<tr><td></td><td>Kumar</td><td>Madurai</td></tr>').insertAfter(clickedrow.parents('tr'));
}
}
else {
clickedrow.attr('src', "http://renko-server/sample/arun/jquery/images/plus.gif");
subrow.hide();
}
}
Demo
Or if you don't want to use onclick direct on image Try this

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

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/

How to access the contents of a cell in HTML table using the cell id?

I have created a table in HTML using JavaScript functions insertRow() and insertCell() functions. I have assigned an id for each cell. I would like to get the value/content of the cell in JavaScript.
Following is the code used to create the table:
<HTML>
<HEAD>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.id = rowCount;
var cell1 = row.insertCell(0);
cell1.id = rowCount + 'a';
cell1.innerHTML = "CELL1";
var cell2 = row.insertCell(1);
cell2.id = rowCount + 'b';
cell2.innerHTML = "CELL2";
var cell3 = row.insertCell(2);
cell3.id = rowCount + 'c';
cell3.innerHTML = "CELL3";
var cell4 = row.insertCell(3);
cell4.id = rowCount + 'd';
cell4.innerHTML = "CELL4";
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<thead>
<TD>Column 1</TD>
<TD>Column 2</TD>
<TD>Column 3</TD>
<TD>Column 4</TD>
</thead>
</TABLE>
</BODY>
I have already tried out the following options:
alert(document.getElementById(1a));
Null
alert(document.getElementById(1a).value);
Error message: Microsoft JScript runtime error: Unable to get value of the property 'value': object is null or undefined
alert(document.getElementById("dataTable").rows[rowCount].cells[0]);
[Object]
alert(document.getElementById("dataTable").rows[rowCount].cells[0].toString());
[Object]
alert(document.getElementById("dataTable").rows[rowCount].cells[0].value);
undefined
Here's an example of how you get the cell's value.
Given you name them serially (starting with row then a,b,c,d you should be able to access them by id as 1a or 3c. With that said, the following is working (supplemental to what you've posted):
<!-- head -->
<script>
function getVal(cellId){
var cell = document.getElementById(cellId);
document.getElementById('a').innerHTML = cell.innerHTML;
// highlight the cell for visual effect
cell.className = 'target';
setTimeout(function(){ cell.className = ''; }, 1e3);
}
</script>
<!-- /head -->
<!-- body -->
<INPUT type="text" id="q" />
<INPUT type="button" value="Get Value" onclick="getVal(document.getElementById('q').value);" />
<span id="a"></span>
<!-- /body -->
Firstly, you should know the row number.
Use document.getElementById(id) to get the content. For example, id = $rownumber + [abcd]
Table cells have no value attribute, but you can access the content via the innerHTML property or the innerText property. The differences are that the latter has somewhat more limited browser support and it gives the text content, without any tags. Example:
alert(document.getElementById('1a').innerHTML)
If this does not work (as a comment seems to say), then the problem is somewhere else. Then you should post code that actually reproduces the issue.
To access the contents of the cells with your current code you only have to address each cell by the id you gave it, then access the innerHTML atribute:
var myCell = document.getElementById('1c')
var myCellContent = myCell.innerHTML
Remember that you have the heading for each column, so your first row that actually has content will be the '1' and not the '0'.
I am able to access the cell contents using the following piece of code:
document.getElementById("dataTable").rows[rowCount].cells[0].innerHTML

Categories