I need to insert some value into html table dynamically. For example, I have some inputs and then I have a table (about 5 rows), so I have one button which enables a timer. When the timer is stopped I need to insert data into table.
Here is the code, how do I add data to one row?
document.getElementById('d1').innerHTML = document.getElementById('ctrl_ball_size_val').value;
document.getElementById('l1').innerHTML = document.getElementById('ctrl_cilindr_height_val').value;
document.getElementById('t1').innerHTML = document.getElementById('stopwatch').value;
How can I add data (data can be different) to the table row by row?
It is highly recommended to avoid using innerHTML for this task.
I suggest to use the DOM to achieve that.
Here is a quick example on how you can create HTML table dynamically using JavaScript:
var tbl = document.createElement("table");
for(var i=0;i<=10;i++){
var tr = document.createElement("tr");
for(var j=0;j<=10;j++){
var td = document.createElement("td");
td.innerHTML = i*j;
tr.appendChild(td);
}
tbl.appendChild(tr);
}
document.body.appendChild(tbl);
Check out my Live example
If you are using JQuery Simply use:
$('#tableID > tbody > tr').each(function() { //Acess $(this) });
And you Never Need it then?
as per jQuery each loop in table row, just a bit of code:
var table = document.getElementById('tblOne');
var rowLength = table.rows.length;
for(var i=0; i<rowLength; i+=1){
var row = table.rows[i];
//your code goes here, looping over every row.
//cells are accessed as easy
var cellLength = row.cells.length;
for(var y=0; y<cellLength; y+=1){
var cell = row.cells[y];
//do something with every cell here
}
}
Related
I have looked all over but can't find a good answer.
So what I'm wanting to do is highlight multiple rows on a table
Then if you click on a highlighted row it gets un-highlighted.
All of this works for me. The problem I'm having is when I un-highlight a row for some reason it won't highlight again.
function highlight_row() {
var table = document.getElementById("display-table");
var cells = table.getElementsByTagName('td');
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
cell.onclick = function () {
var rowId = this.parentNode.rowIndex;
var rowSelected = table.getElementsByTagName('tr')[rowId];
rowSelected.className += "selected";
$(cell).toggleClass('selected');
}
}
}
I have changed out $(cell) with $(this) and that works but only re highlighting the cell I click on and not the whole row.
I'm at a lose here.
Thanks
If you want to highlight the whole row, you need to get parent tr
cell.onclick = function () {
$(this).parent('tr').toggleClass('selected');
}
I've tried with a stupid way of inserting code for a new table, but not even that seems to work. What would be the proper way?
Here's what I tried to do:
var table = document.getElementsByClassName("test")
[0].getElementsByClassName("tableclass");
for (var i = 0, l = table.length; i < l; i++) {
var content = table[i];
let s = content.innerHTML;
s = s.replace(/table/g, 'table border="1"');
s = s.replace(/tr>[\s\S]*?<tr>[\s\S]*?<td>3/g, 'tr>\r\n<tr>\r\n<td>3');
content.innerHTML = s;
}
And a fiddle: https://jsfiddle.net/d10tk7nr/1/
Also, the reason my stupid way doesn't contain the whole table is because some of the cells where I want to eventually use this would contain random data and I don't know how to skip that.
If you want to create a new HTML-Element, every browser got you covered on that.
var tr = document.createElement('tr');
console.log(tr);
The browser console will show you exactly what you have created - a new HTML element that is not yet part of the DOM:
<tr></tr>
The same goes with the creation of some content for that table row:
var td1 = document.createElement('td'),
td2 = document.createElement('td');
td1.innerText = '5';
td2.innerText = '6';
console.log(td1, td2);
The result will be two td-elements:
<td>5</td> <td>6</td>
Now we have to glue these parts together. Browsers will also have you coverd on this:
tr.append(td1);
tr.append(td2);
console.log(tr);
The result is a complete table row:
<tr><td>5</td><td>6</td></tr>
All we have to do is append this row to your table:
var table = document.querySelector('.test table tbody');
table.append(tr);
The elements you have created are now part of the DOM - child elements of the body of your table to be excact.
Click here for a fiddle
Edit
If you want to insert the new row to a specific place, you have to find the element you that should be next to it and use insertBefore. This would change the the last piece of code to:
var targetTr = document.querySelector('.test table tr:nth-child(2)');
targetTr.parentNode.insertBefore(tr, targetTr);
If you want to choose where to put your new row within your javascript, you can use the childNodes property:
console.log(table.childNodes);
I'd use insertAdjacentHTML, like so:
table[i].insertAdjacentHTML('beforeend', '<tr><td>5</td><td>6</td></tr>');
Please see this fiddle: https://jsfiddle.net/52axLsfn/4/
Also demonstrates how to set the border. Note that this code targets all tables, so depending on your situation you may want to be more specific.
I am generating a table row which has two columns dynamically in html containing values from the database.
I want every td of the first column to have an unique id which i have done but i cant set the id to the td of last row in the table.
Here's the code to set id
<script>
var i=0;
var id=1;
while(i<100)
{
document.getElementsByTagName("td")[i].setAttribute("id", id);
i=i+2;
id=id+1;
}
</script>
Any help will be appreciated
but i cant set the id to the td of last row in the table.
You need to get to the last row in the table first.
var allRows = document.getElementsByTagName("tr");
var lastRow = allRows[allRows.length - 1];
now set Id to the first td of last row
lastRow.getElementsByTagName("td")[0].setAttribute("id" , allRows.length + 1 );
DOM Selectors are provided for a reason. :)
var tds = $('tr td:first-child');
var i=0;
$.each(tds, function(){
$(this).attr('id',i++);
});
OR
Using pure javascript
var tds = document.querySelectorAll('tr td:first-child');
var i = 0;
for(var td in tds){
tds[td].setAttribute('id',i++);
// or
//tds[td].id=(i++).toString();
};
You can use querySelectorAll to get all first td's withing given table using :first-child;
It will return NodeList which need to be convert into in an Array.
var arrTD = document.querySelectorAll("#list-notification tr td:first-child");
arrTD = Array.prototype.slice.call(arrTD);
var i =0;
arrTD.forEach(function(val,key){
val.setAttribute('id',i);
++i
})
I have got a working table that when the button is pushed, a table is dynamically created by looping through an array and displaying that data in each cell.
However the problem arises when I am trying to add a table header for my table, and I'm not sure what I am doing wrong.
Here is my current working code: (although doesn't seem to work in JSFiddle?!)
And here is the code I am trying to add: (which must be wrong)
var thd=document.createElement("thead");
tab.appendChild(thd);
var tr= document.createElement("tr");
tbdy.appendChild(tr);
var th= document.createElement("th");
th.appendChild(document.createTextNode("Name");
tr.appendChild(th);
Any help would be greatly appreciated,
You can use a loop to avoid duplicating code. For example:
var columns = ["Name", "Age", "Degree"];
var thd = document.createElement("thead");
tab.appendChild(thd);
var tr = document.createElement("tr");
thd.appendChild(tr);
for (var i = 0; i < columns.length; i++) {
var th = document.createElement("th");
th.appendChild(document.createTextNode(columns[i]));
tr.appendChild(th);
}
Demo: http://jsfiddle.net/ahEkH/6/
I need a code which creates me the table row based on the selection of the dropdown lists.For example if i select 3 then i need 3 rows to be create.I am able to create the rows dynamically but on the change of the ddl value i am not able to delete the previous rows which were getting created.How can i achieve that using jquery or java script.
Thanks Sagar.
So you just want to remove the rows from the table and then add X amount of rows to it?
What you want is the jQuery remove method:
// Get the table and delete the rows
var $table = $("#tableId");
$table.find("tr").remove();
// Get the row count and create the number of rows
var rowCount = GetYourRowCount();
for (var i = 0; i < rowCount; i++)
{
var $tr = $("<tr>");
$table.append($tr);
}