How to add a table row or table column at specific index by on clicking the table cells, same as excel sheet.
<table >
<tr>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Add Row Script:
function AppendRows() {
var tableRows = document.getElementById('myTable'),
row = tableRows.insertRow(tableRows.rows.length);
row.height = '50';
for (var i = 0; i < tableRows.rows[0].cells.length; i++) {
row.insertCell(i), i, 'row';
}
}
Here is an example on how you can insert a new row. There are several approaches you can go with but basically this is the way
function insertrow() {
var newRowIndex = 1;
var row1 = document.getElementById("table").childNodes[1].childNodes[newRowIndex];
var newRow = document.createElement("tr");
var col0 = document.createElement("td");
col0.innerHTML = "newA";
newRow.appendChild(col0);
var col1 = document.createElement("td");
col1.innerHTML = "newB";
newRow.appendChild(col1);
var col2 = document.createElement("td");
col2.innerHTML = "newC";
newRow.appendChild(col2);
row1.parentNode.insertBefore(newRow, row1);
}
<button onclick="insertrow()">Insert row</button>
<table id="table">
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
<tr>
<td>d</td>
<td>e</td>
<td>f</td>
</tr>
</table>
Also i'd suggest you take a look at the insertBefore documentation.
Here's a method to insert a row after a row is clicked. The new row is added immediately after the clicked row, so new rows can be added at different locations.
Let's walk through it:
First we setup an event listener on the table to listen for clicks on the row elements. When a row is clicked, we call the the appendRow method to add a new row, and pass the index where we want the row to appear.
We're using delegation here so dynamically added rows will be included in the event listener.
The appendRow method adds a new row at the defined index, then adds a few table cells for presentation purposes.
var tableEl = document.getElementById('table');
tableEl.addEventListener('click', function(event) {
var el = event.target;
if (el.closest('tr') && el.closest('tbody')) {
var trow = el.parentElement;
var tbody = trow.parentElement;
var index = Array.prototype.indexOf.call(tbody.children, trow);
appendRow(tbody, index + 1);
}
});
function appendRow(tbody, index) {
var row = tbody.insertRow(index);
var cells = ['A', 'B', 'C'];
cells.forEach(function(cell, idx) {
var newCell = row.insertCell(idx);
var newText = document.createTextNode(`Row ${index} - ${cell}`);
newCell.appendChild(newText);
});
}
table {
table-layout: fixed;
width: 100%;
}
td {
border: 1px solid gray;
}
<table id="table">
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>B</td>
<td>C</td>
</tr>
</tbody>
</table>
Related
I have a problem with jQuery script. I'm trying to make a simple counting loop, for each tr. I got a table like below, and I want to select the second td, multiply it by two and add to the third td and display the result in the fourth td.
https://codepen.io/adeowsky/pen/YEgVKG
I'm trying to make it with the for each loop like below ->
<script>
(function($) {
$('.sp-league-table tbody tr').each( function() {
var pct = this.find('.data-pct').text();
console.log(pct);
//var pct = $('').hasClass('data-pct').text();
//console.log(pct);
var winy = $('.data-w').text();
var losy = $('.data-l').text();
/*var pkt = (winy*2) + (losy*2);
$('.data-pct').text(pkt);*/
});
})( jQuery );
</script>
But it doesn't work for me, where is the reason?
You are selecting all the elements with the class, not the one in the current row.
var tr = $(this);
var pCell = tr.find(".data-pct")
var wCell = tr.find('.data-w')
var lCell = tr.find('.data-l')
There are a couple of problems
Your table does not have the required class
you're not targeting the specific row's cells
You should explicitly parse the string values to integers
you've commented out the bit that does the calculation:
$(function(){
$('.sp-league-table tbody tr').each( function() {
var pct = $('.data-pct',this).text();
var winy = parseInt($('.data-w',this).text(),10);
var losy =parseInt($('.data-l',this).text(),10);
var pkt = (winy*2) + (losy*2);
$('.data-pct',this).text(pkt);
});
})
Updated: https://codepen.io/anon/pen/NwJjaO
Live example:
$(function(){
$('.sp-league-table tbody tr').each( function() {
var pct = $('.data-pct',this).text();
var winy = parseInt($('.data-w',this).text(),10);
var losy =parseInt($('.data-l',this).text(),10);
var pkt = (winy*2) + (losy*2);
$('.data-pct',this).text(pkt);
});
})
table, tr, td, th {
border: 1px solid #000;
border-collapse: collapse;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="sp-league-table">
<thead>
<tr>
<th>Name</th>
<th>W</th>
<th>L</th>
<th>PCT</th>
</thead>
<tr>
<td>Name 1</td>
<td class="data-w">12</td>
<td class="data-l">0</td>
<td class="data-pct">x</td>
</tr>
<tr>
<td>Name 2</td>
<td class="data-w">9</td>
<td class="data-l">3</td>
<td class="data-pct">x</td>
</tr>
</table>
<table class="sp-league-table">
<thead>
<tr>
<th>Name</th>
<th>W</th>
<th>L</th>
<th>PCT</th>
</thead>
<tr>
<td>Name 1</td>
<td class="data-w">12</td>
<td class="data-l">0</td>
<td class="data-pct">24</td>
</tr>
<tr>
<td>Name 2</td>
<td class="data-w">6</td>
<td class="data-l">5</td>
<td class="data-pct">17</td>
</tr>
</table>
Lets say we have an Array that looks like this
(example)
Array1 = [Data_A,Data_B];
Array2 = [Data_1,Data_2,Data_3];
and I have a table that looks like this
How can I achieve this?
For now I can retreive the data in row order using for loop and this is my code
for (i = 0; i < Array1 .length; i++) {
for (x in Array1 [i]) {
console.log(data from array);
}
}
My target here is for every array is I need to make it as a row for every col. for example Array1 is fol Col1 and also note that my arrays are fixed for each col. col3 and 4 are for ex. only
Because the data in table columns don't usually change unlike they do in rows, I highly discourage managing table data by columns. It is best to do it by rows.
What I mean is to have Row1 = [Data_A, Data_1]; and Row2 = [Data_B, Data_2]; and so on, rather than how you had it set up.
function CreateRow(data) {
var tr = "<tr>"
for (var i = 0; i < data.length; i++) {
tr += "<td>" + data[i] + "</td>";
}
tr += "</tr>"
$('#table').append(tr);
}
function EditRow(data, rowIdx) {
var tr = $('#table').children().eq(0);
for (var i = 0; i < data.length; i++) {
tr.children().eq(i).text(data[i]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Data 0</td>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
<button type="button" onclick="CreateRow(['A','B','C','D'])">Create Row</button>
<button type="button" onclick="EditRow(['EditedData1','EditedData2', 'EditedData3', 'EditedData4'], 0)">Edit First Row</button>
(Pure Javascript snippet for those who are interested)
function CreateRow(data) {
var table = document.getElementById("table");
var tr = document.createElement("tr");
for (var i = 0; i < data.length; i++) {
var td = document.createElement("td");
td.appendChild(document.createTextNode(data[i]));
tr.appendChild(td);
}
table.appendChild(tr);
}
function EditRow(data, rowIdx) {
var tr = document.getElementById("table").getElementsByTagName("tr")[rowIdx];
for (var i = 0; i < data.length; i++) {
tr.getElementsByTagName("td")[i].innerHTML = data[i];
}
}
<table>
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
</thead>
<tbody id="table">
<tr>
<td>Data 0</td>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
</tr>
</tbody>
</table>
<button type="button" onclick="CreateRow(['A','B','C','D'])">Create Row</button>
<button type="button" onclick="EditRow(['EditedData1','EditedData2', 'EditedData3', 'EditedData4'], 0)">Edit First Row</button>
I am trying to add rows to an existing table that has header and footer also.
Here is my code:
<script>
function test() {
var tbl = document.getElementById("tbl");
var lastRow = tbl.rows.length - 1;
var cols = tbl.rows[lastRow].cells.length;
var row = tbl.insertRow(-1);
for (var i = 0; i < cols; i++) {
row.insertCell();
}
}
</script>
<table id="tbl" onclick="test()">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
when I click on any table I want to add new row to table body, but the issue here is the new row is added to table footer. please help me how to fix this issue.
You insert the row into the tBody element. Since there can be more than one tBody, you should refer to the tBodies prop of table at index 0.
var row = tbl.tBodies[0].insertRow(-1);
function test() {
var tbl = document.getElementById("tbl");
var lastRow = tbl.rows.length - 1;
var cols = tbl.rows[lastRow].cells.length;
var row = tbl.tBodies[0].insertRow(-1);
for (var i = 0; i < cols; i++) {
row.insertCell().appendChild(document.createTextNode(i));
}
}
test();
<table id="tbl" onclick="test()">
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Sum</td>
<td>$180</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</tbody>
</table>
Try something like this. Just clone first row and then append it as child to your table. Hope it will help you
function appendRow() {
let tbl = document.getElementById("tbl");
let newRow = tbl.rows[0].cloneNode(true);
tbl.appendChild(newRow);
I'm trying to use the sorttable.js package to make an HTML table sortable when the column header is clicked. I can get this to work just fine when the table is declared statically in the HTML:
fiddle
<table class="sortable" style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Points</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>Joe</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Abraham</td>
<td>Jones</td>
<td>4</td>
</tr>
</table>
However, when I create the table with javascript, the sorting functionality isn't there anymore, and I get error messages on the console:
fiddle
tbl_array = new Array()
tbl_array = [["Firstname","Lastname","Points"], ["Eve","Jackson","94"], ["Joe","Smith","50"], ["Abraham","Jones","4"]]
var body = document.body,
tbl = document.getElementById('summaryTable');
// clear all rows on the table
while(tbl.rows.length > 0){
tbl.deleteRow(0)
}
tbl.style.width = '100px';
tbl.style.border = '1px solid black';
numRows = tbl_array.length
numCols = tbl_array[0].length
// insert each 2D array entry into a table cell
for(var i = 0; i < numRows; i++){
// insert header
if (i == 0){
var header = tbl.createTBody();
var row = header.insertRow();
for (var j=0; j < numCols; ++j){
var cell = document.createElement('th')
cell.appendChild(document.createTextNode(tbl_array[i][j]));
cell.style.border='1px solid black';
cell.style.fontWeight = "bold";
row.appendChild(cell)
}
}
else{
var tr = tbl.insertRow();
for(var j = 0; j < numCols; j++){
var td = tr.insertCell();
td.appendChild(document.createTextNode(tbl_array[i][j]));
td.style.border = '1px solid black';
}
}
}
console.log("tbl", tbl)
The only thing I can think of is that I'm not formatting the table correctly with the javascript, but when I printed both tables to the console and examined their structures, they were basically the same:
<table ...>
<tbody>
<tr ...>
<th>..</th>
<th>..</th>
</tr>
<tr>
<td>..</td>
<td>..</td>
</tr>
</tbody>
</table>
Is my error in the way I'm creating the table with javascript? Any help would be appreciated. Thanks!
sorttable.js assumes all tables are already in the HTML when it initializes; your table is dynamically generated, so you have to bootstrap the makeSortable method manually.
Right before your console.log, try inserting this:
sorttable.makeSortable(document.getElementById('summaryTable'));
Am trying to add a :before to a td element in my table with content same as the value as the th in the same column, i got to the point where i can change the value of the td but im stuck at adding the :before, here is my code:
function myFunction() {
var rows = document.getElementsByTagName("table")[0].rows;
var last = rows[0];
var first = rows[1];
for (i = 0; i < 2; i++) {
var cell = last.cells[i];
var value = cell.innerHTML;
alert(value);
first.cells[i].innerHTML = value;
}
}
<table>
<thead>
<tr>
<th>aa</th>
<th>bb</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>4</td>
</tr>
</tbody>
</table>
<button onclick="myFunction()">Test</button>
You can't add :before to element with JavaScript. But you can do it with CSS:
td:before {
content: attr(data-content);
}
<td data-content="content for :before">
actual content
</td>
And then just change data-content attribute on td with JavaScript.