Select the highlighted row of dynamically created table,onclick event - javascript

I have created a web page generating dynamic table depending on the data length. Now i want to fetch the value of selected tr of table and append it into another table.
function setItemForSale(itemForSale, type,xml)
{
var itemForSaleTable = document.getElementById("custorder1");
var itemForSaleTableHead = document.getElementById("head1");
var itemForSaleTableBody = document.createElement("tbody");
itemForSaleTableBody.appendChild(itemForSaleTableHead);
$('#custorder1 tr').has('td').remove();
for(var i=0; i< itemForSale.length; i++)
{
var row = document.createElement("tr");
itemForSaleTable.insertRow(-1);
var obj = itemForSale[i];
var vitemno = obj["itemNo"];
var vname = obj["name"];
var valias = obj["alias"];
var vbrand = obj["brand"];
var vdescription = obj["description"];
var cell = document.createElement("td");
var cellText = document.createTextNode(vitemno);
cell.appendChild(cellText);
row.appendChild(cell);
cell = document.createElement("td");
cellText = document.createTextNode(vname);
cell.appendChild(cellText);
row.appendChild(cell);
cell = document.createElement("td");
cellText = document.createTextNode(valias);
cell.appendChild(cellText);
row.appendChild(cell);
cell = document.createElement("td");
cellText = document.createTextNode(vbrand);
cell.appendChild(cellText);
row.appendChild(cell);
cell = document.createElement("td");
cellText = document.createTextNode(vdescription);
cell.appendChild(cellText);
row.appendChild(cell);
itemForSaleTableBody.appendChild(row);
}
itemForSaleTable.appendChild(itemForSaleTableBody);
itemForSaleTable.setAttribute("border", "2");
}
//code for creating table skeleton
<table class="CSSTableGenerator" id="custorder1" >
<thead>
<tr id="head1">
<th>
Item No
</th>
<th>
Name
</th>
<th>
Alias
</th>
<th>
Brand
</th>
<th>
Description
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
//I want to pick the individual cells data so that i can use it to fetch data. How to pick any cell data in selected row, I don't know how to do it! Help me Please

You can bind click handler on tr then use .appendTo() to move the selected row to another table.
$('#custorder1').on('click', 'tr', function(){
$(this).appendTo('#anotherTableId')
});
$('#custorder1').on('click', 'tr', function() {
$(this).appendTo('#anotherTableId')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="CSSTableGenerator" id="custorder1">
<thead>
<tr>
<th>
Item No
</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
</tbody>
</table>
Another table
<table class="CSSTableGenerator" id="anotherTableId">
</table>

Related

Can't loop through table in javascript

I am new to javascript and am currently trying to loop through table rows to get the data from it however its showing an error that it can't recognize rows for table.
<div class="row" id="tablediv">
<div class="col">
<table class="table table-striped table-bordered" id="table"/>
</div>
</div>
var table = document.getElementById('#table');
for (let i in table.rows) {
let row = table.rows[i];
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
console.log(row);
for (let j in row.cells) {
let col = row.cells[j];
//iterate through columns
//columns would be accessed using the "col" variable assigned in the for loop
console.log(col);
}
}
offices:1048 Uncaught TypeError: Cannot read properties of null (reading 'rows')
at save (offices:1048:25)
at HTMLButtonElement.onclick (offices:101:84)
Am I doing something wrong or is there a workaround for that?
Your table variable must be declare before.
You can do this :
<table id="myTab1">
<thead>
<tr>
<th scope="col">First</th>
<th scope="col">Last</th>
<th scope="col">Handle</th>
</tr>
</thead>
<tbody>
<tr class="rowTable">
<td>Mark</td>
<td>Otto</td>
<td>#mdo</td>
</tr>
<tr class="rowTable">
<td>Jacob</td>
<td>Thornton</td>
<td>#fat</td>
</tr>
<tr class="rowTable">
<td>Larry</td>
<td>the Bird</td>
<td>#twitter</td>
</tr>
</tbody>
</table>
<script>
var table = document.getElementById("myTab1");
for (let i = 0; i < table.rows.length; i++) {
let row = table.rows[i]
for (let j = 0; j < row.cells.length; j++) {
let cell = row.cells[j];
console.log(cell.textContent)
}
}
You have to target the table first. With var table = document.getElementById("myTable");, you can store in a variable table and then loop through.
In your example, this would look like var table = document.getElementById("table");
Also check this How do I iterate through table rows and cells in JavaScript?

Write values to td with no id?

I need to edit values in a table where the rows/cells are generated dynamically so I they have no html id. I am currently doing this by going to tr:nth-child, but this only works if the value I set for rowID corresponds to that position in the table. Ex: If I remove the 3rd item from the table, the item with rowID=4 is now the 3rd child of the tr, and the following code will edit the wrong cells.
// I get the rowID like this:
rowID = $(this).data("row-id");
// This is what I'm doing now to edit the table:
$('#or-table tr:nth-child(' + rowID + ') td:nth-child(3)').html($('#aff-selector').val());
$('#or-table tr:nth-child(' + rowID + ') td:nth-child(4)').html($('#editor-code').val());
$('#or-table tr:nth-child(' + rowID + ') td:nth-child(5)').html($('#editor-lat').val());
$('#or-table tr:nth-child(' + rowID + ') td:nth-child(6)').html($('#editor-long').val());
<!-- This is the table: -->
<table id="or-table" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th data-column-id="id" data-identifier="true" data-type="numeric">ID</th>
<th data-column-id="aff" align="center">Affiliation</th>
<th data-column-id="code">Symbol Code</th>
<th data-column-id="lat">Latitude</th>
<th data-column-id="long">Longitude</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
<tbody></tbody>
</table>
You could dynamically assign the row ids using a for loop and then redo that calculation every time you remove a row.
function foo () {
var rowCount = $('#or-table tbody tr').length;
for (i=1;i <= rowCount; i++) {
$('#or-table tbody tr:nth-child("'+i+'")').data('row', i);
}
}
You could run this function on $(document).ready and again after the removal of any row.
Use the HTMLTableElement interface. BTW, why would you need to remove a <td>? Wouldn't be easier just to remove the data inside the <td>?
Get a reference to the <table>
-var or = document.getElementById('or-table');
Then use the .rows property.
-or.rows[0] // first row of table
Next, use the .cells property.
-or.rows[0].cells[2] // first row, 3rd cell
Finally, edit the value of cell with innerHTML or textContent.
-or.rows[0].cells[2].innerHTML='test' // set first row, 3rd cell content to "test"
The following Snippet demonstrates the use of the HTMLTableElement interface:
SNIPPET
var or = document.getElementById('or-table');
function seekCell(row, cell) {
var data = document.getElementById('data').value;
var row = parseInt(row, 10);
var cell = parseInt(cell, 10);
var rows = or.rows.length; // max number of rows
var cells = rows * 6; //max number of cells
(row > rows) ? row = rows: row = row - 1;
(cell > cells) ? cell = cells: cell = cell - 1;
var tgt = or.rows[row].cells[cell];
tgt.innerHTML = data;
}
[type='number'] {
width: 30px;
}
<!-- This is the table: -->
<table id="or-table" class="table table-condensed table-hover table-striped bootgrid-table">
<thead>
<tr>
<th data-column-id="id" data-identifier="true" data-type="numeric">ID</th>
<th data-column-id="aff" align="center">Affiliation</th>
<th data-column-id="code">Symbol Code</th>
<th data-column-id="lat">Latitude</th>
<th data-column-id="long">Longitude</th>
<th data-column-id="commands" data-formatter="commands" data-sortable="false">Commands</th>
</tr>
</thead>
<tbody>
<tr>
<td>01</td>
<td>NONE</td>
<td>🗡</td>
<td>20</td>
<td>30</td>
<td>KILL</td>
</tr>
<tr>
<td>02</td>
<td>NONE</td>
<td>🖉</td>
<td>30</td>
<td>30</td>
<td>EDIT</td>
</tr>
</tbody>
</table>
<form id='f1' name='f1' onsubmit='seekCell(row.value, cell.value)'>
<fieldset>
<legend>Row & Cell</legend>
<label>Row:
<input id='row' name='row' type='number' min='1' max='99'>
</label>
<label> <small>Note: The first row is the <thead></small>
</label>
<br/>
<label>Cell:
<input id='cell' name='cell' type='number' min='1' max='6'>
</label>
<label><small> Note: The number will be adjusted for 0-Index enumeration. (i.e. input -1)</small>
</label>
<br/>
<label>Data:
<input id='data'>
</label>
<input type='submit'>
</fieldset>
</form>

transfer table values into another table using onclick

i need help guys i want to know how to transfer a table row value into another table row using onclick already know how to get the value using the onclick but dont know how to transfer the values into the table
<html>
<body>
<table class='list'>
<thead>
<tr>
<th class='idno'>ID No.</th>
<th class='itemn'>Item</th>
<th class='quant'>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Chocolate</td>
<td>99</td>
</tr>
<tr>
<td>2</td>
<td>Bread</td>
<td>99</td>
</tr>
</tbody>
</table>
<script>
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
};
</script>
</body>
</html>
You need to create some nodes. Create a <tr> first. Then loop the following: create a <td>, then a text node from the data that you have already collected, append the text into the <td> then the <td> into the <tr> and repeat the loop. Finally append the <tr> to the table body. Run the code snippet below.
<html>
<body>
<table class='list'>
<thead>
<tr>
<th class='idno'>ID No.</th>
<th class='itemn'>Item</th>
<th class='quant'>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Chocolate</td>
<td>99</td>
</tr>
<tr>
<td>2</td>
<td>Bread</td>
<td>99</td>
</tr>
</tbody>
</table>
<br><br>
MY NEW TABLE
<table class='list'>
<thead>
<tr>
<th class='idno'>ID No.</th>
<th class='itemn'>Item</th>
<th class='quant'>Quantity</th>
</tr>
</thead>
<tbody id='myNewTableBody'></tbody>
</table>
<script>
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
var trnode = document.createElement("tr");
for(var i = 0; i < data.length; i++){
var tdnode = document.createElement("td");
var textnode = document.createTextNode(data[i]);
tdnode.appendChild(textnode);
trnode.appendChild(tdnode);
}
document.getElementById("myNewTableBody").appendChild(trnode);
alert(data);
};
</script>
</body>
</html>
I have modified your code, look into this
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
// get other table you want to insert in
var t2 =document.getElementById("othertable");
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
//insert at zero index
var tr = t2.insertRow(0)
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
var cell = tr.insertCell(i);
cell.innerHTML = cells[i].innerHTML;
}
}
alert(data);
};
<table class='list'>
<thead>
<tr>
<th class='idno'>ID No.</th>
<th class='itemn'>Item</th>
<th class='quant'>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Chocolate</td>
<td>99</td>
</tr>
<tr>
<td>2</td>
<td>Bread</td>
<td>99</td>
</tr>
</tbody>
</table>
<hr/>
<table id="othertable"></table>

using jquery on javascript built table

I built an table using JavaScript. However when I try to call jQuery on that table it doesnt work. I am trying to make jQuery highlight the columns of the table when I hoover with it.
Here is my code
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(tableRef.rows.length);
// 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 row')
// Append a text node to the cell
newCell.appendChild(newText);
//Apend new cell to same row
var newCell = newRow.insertCell(1);
var newText = document.createTextNode('Nea')
newCell.appendChild(newText);
//highlight column
$('td').on('mouseenter', function() {
var i = $(this).parent().children().index(this);
$('col').removeClass('hovered');
$('col:nth-child(' + (i + 1) + ')').addClass('hovered');
});
$('td').on('mouseleave', function() {
$('col').removeClass('hovered');
});
table {
border-collapse: collapse;
}
table tr:hover {
background-color: grey;
}
col.hovered {
background-color: grey;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
Here is JsFiddle
http://jsfiddle.net/4sR2G/764/
I managed to get the effect using
<colgroup>
<col></col>
<col></col>
<col></col>
</colgroup>
From one of the examples you gave.

Javascript: extract cell data from table

I have a scenario where there is a table of 4 rows, in the 4th row is a textbox. When an "onchange" event of the textbox is triggered, I want to extract the data in the cells of the same specific row into another table. and ofcourse my table is consisted of more than one row.
<div class="ProductsTable">
<table class="tablestyle">
<tr>
<th>Item</th>
<th>Price</th>
<th>Preview</th>
<th class="auto-style4">Quantity</th>
<th class="auto-style15">Selected Items</th>
</tr>
<tr id="row1">
<td class="auto-style1" id="item_name">Sofa</td>
<td class="auto-style2" id="item_price">$280.00</td>
<td class="auto-style3">
<img class="itemimage" src="images\sofa1.jpg" />
</td>
<td class="auto-style4">
<input class="quantitybox" id="item_quantity" type="text" onchange="get_quantity();" />
</td>
<td rowspan="10">
<table class="InvoiceTable" id="invoice">
<tr>
<th class="auto-style7">Item</th>
<th class="auto-style2">Price</th>
<th class="auto-style4">Quantity</th>
</tr>
</table>
</td>
</tr>
</table>
</div>
And my javascript is:
function get_quantity() {
var table = document.getElementById("invoice");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2)
cell1.innerHTML = document.getElementById("item_name").innerHTML;
cell2.innerHTML = document.getElementById("item_price").innerHTML;
cell3.innerHTML = document.getElementById("item_quantity").value;
}
How can I create a loop to check through all my table when an "onchange" event is triggered. As I actually have 10 rows in my table.
Preferably without using jquery.
If I understand you correctly you are looking for a function to copy the content of the changed row, that is the data in each column, into the invoice table.
I expect the rows to be created dynamicaly with some sort of iteration. When iterating I expect a unique number is availabe why this can be used as a general selector.
Here is a function to do this:
function get_quantity(rowNumber) {
var table = document.getElementById("invoice" + rowNumber);
var row = table.insertRow(1);
var columns = document.getElementById("row" + rowNumber).childNodes;
var dataColumnIndex = 0;
for (var i = 0; i < columns.length; i++) {
if (columns[i].className == "data") {
var cell = row.insertCell(dataColumnIndex);
cell.innerHTML = columns[i].innerHTML;
dataColumnIndex++;
}
}
var inputQuantity = document.getElementById("item_quantity" + rowNumber).value
row.insertCell(dataColumnIndex).innerHTML = inputQuantity;
}
You select what columns to copy by marking the them with class data.
I gets the invoice table by expecting it to have the id invoice + number. Fx. invoice1. Same goes with each row and the input field.
Here is a plunker with a full example.
Edit
There should only be a single invoice table where all products are added to.
By selecting the same table for row insertion in the function this is fixed.
This updated plunker has the change

Categories