I am trying to read all rows from a dynamic table. The main idea is to read all the rows and store it in an array for further processing. But so far I have not been able to get the row data. The code below only returns the table headers.
Here is the code:
var data = [];
var i = 0;
$('#tempTable td').each(function (index, tr) {
var tds = $(tr).find('td');
if (tds.length > 1) {
data[i++] = {
action: tds[0].textContent,
spec: tds[1].textContent,
data: tds[2].textContent,
unit: tds[3].textContent,
upper_tol: tds[4].textContent,
lower_tol: tds[5].textContent,
tol_unit: tds[6].textContent,
def: tds[7].textContent
}
}
});
And the HTML markup looks like this:
<table id='tempTable'>
<thead>
<tr>
<td class='table_head' width='80px'>Header1</td>
<td class='table_head' width='435px'>Header2</td>
<td class='table_head' width='100px'>Header3</td>
<td class='table_head' width='100px'>Header4</td>
<td class='table_head' width='100px'>Header5</td>
<td class='table_head' width='100px'>Header6</td>
<td class='table_head' width='100px'>Header7</td>
<td class='table_head' width='80px'>Header8</td>
</tr>
</thead>
<tbody>
<!-- Rows inserted dynamically here using jQuery -->
</tbody>
</table>
You have initialized your table headers as 'td' instead you need to initialize them in 'th' as below..
<table id='tempTable'>
<thead>
<tr>
<th class='table_head' width='80px'>Header1</th>
<th class='table_head' width='435px'>Header2</th>
<th class='table_head' width='100px'>Header3</th>
<th class='table_head' width='100px'>Header4</th>
<th class='table_head' width='100px'>Header5</th>
<th class='table_head' width='100px'>Header6</th>
<th class='table_head' width='100px'>Header7</th>
<th class='table_head' width='80px'>Header8</th>
</tr>
</thead>
<tbody>
<!-- Rows inserted dynamically here using jQuery -->
</tbody>
</table>
Also see the at which event you are selecting table data(Before selection table should be filled with data).
For selecting the data from table :
//traverse each row
$('#tempTable tr').each(function (index, tr) {
var cols = [];
//get td of each row and insert it into cols array
$(this).find('td').each(function (colIndex, c) {
cols.push(c.textContent);
});
//insert this cols(full rows data) array into tableData array
tableData.push(cols);
});
console.log("tableData: ", tableData);
Please find the fiddle https://jsfiddle.net/Prakash_Thete/frm2ebug/1/ for the same..
Related
I have my code for a table that I created in html with one row, but I want to add more rows to it, the number of total rows has to be equal to the value that my combox takes (24,36,48 rows in total):
<div id="visible" class="table-responsive">
<table class="table " id="tablacondatos" name="tablacondatos">
<thead>
<tr>
<th scope="col">MES</th>
<th scope="col">CUOTA</th>
<th scope="col">INTERES</th>
<th scope="col">AMORTI.</th>
<th scope="col">CAPITAL</th>
<th scope="col">SEGURO DESGRAV.</th>
<th scope="col">SEGURO INMOBIL.</th>
<th scope="col">GASTOS ADM.</th>
<th scope="col">CUOTA FINAL</th>
</tr>
</thead>
<tbody id="cuerpotabla" name="cuerpotabla">
<tr id="filamaestra">
<td id="mes" name="mes">0</td>
<td id="cuota" name="cuota">0</td>
<td id="interes" name="interes">0</td>
<td id="amorti" name="amorti">0</td>
<td id="capital" name="capital">0</td>
<td id="segurodesgrav" name="segurodesgrav">0</td>
<td id="seguroinmobil" name="seguroinmobil">0</td>
<td id="gastosadm" name="gastosadm">0</td>
<td id="cuotafinal" name="cuotafinal">0</td>
</tr>
</tbody>
</table>
</div>
This is how I get the value of my combo for the rows:
ahorrar = document.getElementById("plazooperacion").value; // 24,36,48 rows
I am using this code to add rows, but the problem is that it generates too many rows, and in the first cells I am putting a counter, which goes from 1 to 24, or 1 to 36 or from 1 to 48; but it generates them backwards (it puts the last one first and the first one last):
ms=ms+1; //accountant
var table = document.getElementById("cuerpotabla");
var row = table.insertRow(0);
//this adds row in 0 index i.e. first place
row.innerHTML = "<td>"+ms+"</td><td id='cuota' name ='cuota'>"+cuota+"</td><td id='interes' name='interes'>"+interes+"</td><td id='amorti' name='amorti'>"+amorti+
"</td><td id='capital' namre='capital'>"+capital+"</td><td id='segurodesgrav' name='segurodesgrav'>"+segurodesgrav+"</td><td id='seguroinmobil' name='seguroinmobil'>"+seguroinmobil+"</td><td id='gastosadm' namre='gastosadm'>"+gastosadm+"</td><td id='cuotafinal' name='cuotafinal'>"+cuotafinal+"</td>";
I have a html table with multiple rows and columns. I want to pull all the values by column id and compare with some matching string. If matches i want to enable a button on the page.
Could you please let me know how to refer the column by id in $(document).ready function.
Here is the table
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<th:block th:each="it : ${data}">
<tr>
<td th:text="${it.id}">id</td>
<td th:text="${it.name}">name</td>
<td th:text="${it.place}">place</td>
</tr>
</th:block>
</table>
Button:
style="visibility:hidden">Submit
$(document).ready(function(){
//here i want to pull the place column and verify if one of the
places matches my input string enable submit button
$("#submitbutton").css("visibility", "visible");
}
}
This function will take all information inside you td and search for the string you looking for :
But i cannot get the point that you search for a particular string instead of searching for an object.
const addresses = [...document.querySelectorAll(".address")];
const serchFromList = (arr, str) => {
return arr.map(el =>
el = el.innerHTML
).filter(el => el === str)
}
console.log(serchFromList(addresses, "NY"))
/* in case you want a boolean you can use some*/
const isAddressExist = (arr, str) => {
return arr.map(el =>
el = el.innerHTML
).some(el => el === str)
}
console.log(isAddressExist(addresses, "NY"))
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<th>
<tr>
<td>4545</td>
<td>5454</td>
<td>65687</td>
</tr>
<tr>
<td>aziz</td>
<td>david</td>
<td>paul</td>
</tr>
<tr>
<td class='address'>NY</td>
<td class='address'>MTL</td>
<td class='address'>BC</td>
</tr>
</th>
</table>
Should be pretty doable with XPath if you don't want to add extra attributes to Place cell. Just find out the position of Place column and get the text from the same position of <td>.
// Get the table node first
let node = document.getElementById('data')
// Find out position of `Place` column
let nth = document.evaluate('count(//th[text()="Place"]/preceding-sibling::*)+1', node).numberValue
// Get all the place cell by the position
let placeCells = document.evaluate(`//td[position()=${nth}]`, node)
// Get all the place names
let places = [],
placeNode = placeCells.iterateNext()
while (placeNode) {
places.push(placeNode.textContent)
placeNode = placeCells.iterateNext()
}
console.log(places)
// ['NYC', 'SF', 'LA']
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<tbody>
<tr>
<td>0001</td>
<td>Mary</td>
<td>NYC</td>
</tr>
<tr>
<td>0002</td>
<td>John</td>
<td>SF</td>
</tr>
<tr>
<td>0003</td>
<td>Bob</td>
<td>LA</td>
</tr>
</tbody>
</table>
I would like to know how could I assign a table row an id which is systematically as a counter. It can be a string + a counter as follow:
<table>
<tr id="Row1"> # it can be only a number => id="1"
<tr id="Row2"> # it can be only a number => id="2"
<tr id="Row3"> # it can be only a number => id="3"
.....
<tr id="Row5000"> # it can be only a number => id="5000"
</table
Because I have thousands of rows and then could not assign id to them manually. This is why I want to assign them via XSLT. Does anybody know how could I do so? Thanks.
// javascript
var table = document.querySelectorAll('table tr');
{
for(var i=0;i<table.length;i++){
table[i].setAttribute("id",i+1);
}
//jquery
$("table tr").each(function(index,object) {
object.attr("id",(index+1));
})
$("table tr").each(function(i, tr) {tr.id = 'Row' + (i+1);})
explanation: you can find each tr in table and assign id for each one.
First you assign an id attribute to your table like this
<table id="mytable">
<tr></tr>
<tr></tr>
....
</table>
Then add a script at the bottom of your document
<script>
(function() {
var rows = document.getElementById("mytable").rows;
for(var i = 1; i <= rows.length; i++) {
rows[i-1].id = 'Row'+i;
}
})();
Its a pure javascript solution. No jQuery required.
Assign your table an id. here its newTable then iterate and set the attibute
<script>
function getit(){
$('#newTable').find('tr').each(function(index){
var x= this.setAttribute("id","Row"+[index]);
console.log(x);
})
}
</script>
hope that helped.
You Can Use This:
Your CSS
<style>
body {
counter-reset: section;
}
table tbody tr th::before {
counter-increment: section;
content: "Section " counter(section);
}
table tbody tr th::before {
content: counter(section);
}
</style>
Your Html
<table class="table">
<thead>
<tr>
<th colspan="6">
</th>
</tr>
<tr>
<th scope="col">#</th>
<th scope="col">f1</th>
<th scope="col">f2</th>
<th scope="col">f3</th>
<th scope="col">f4</th>
<th scope="col">f5</th>
</tr>
</thead>
<tbody>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
<tr>
<th class="align-middle" scope="row"></th>
<td class="align-middle">d1</td>
<td class="align-middle">d2</td>
<td class="align-middle">d3</td>
</tr>
</tbody>
</table>
I'm using html5 and jquery to set up a dynamic table, until then I can add the elements to the table without problems, but I can not retrieve the value of its columns. so I have the following questions:
How can I recover the table data by clicking the ROW?
Should I always use the data-name, id for example as in the first
line ?
$(document).on("change", "#TabClientesAdicionados", function(e) {
alert('?');
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="TabClientesAdicionados" class="table table-hover">
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Actions </th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="Bruno">1</td>
<td data-nome="Bruno">Bruno</td>
<td>Details</td>
</tr>
<tr>
<td>2</td>
<td>Josep</td>
<td> Details </td>
</tr>
</tbody>
</table>
How can I recover the table data by clicking the ROW?
You can bind the click event to your TR elements and get the information.
Should I always use the data-name, id for example as in the first line?
Yes, because you don't want the parsed HTML to manipulate data. The data attributes are a better approach to keep related data (no HTML) to DOM elements.
Look at this code snippet
This approach binds the click event to TR elements
$('#TabClientesAdicionados tbody tr').click(function() {
var data = { name: '', id: '' };
$(this).children('td').each(function() {
var name = $(this).data('nome');
if (name) {
data.name = name;
}
var id = $(this).data('id');
if (id) {
data.id = id;
}
});
console.log(data);
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<hr>
<table id="TabClientesAdicionados" class="table table-hover">
<thead>
<tr>
<th> ID </th>
<th> Name </th>
<th> Actions </th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="Bruno_1">1</td>
<td data-nome="Bruno">Bruno</td>
<td>Details</td>
</tr>
<tr>
<td>2</td>
<td>Josep</td>
<td> Details </td>
</tr>
</tbody>
</table>
I would do as the following snippet.
You need to bind the event to the row tr ant then get each of its children.
By adding a data attribute you could set a column name. This could also help if you eventually needed to extract the value of an specific cell.
Incidentally you could also add a second data attribute named like data-value or something similar- This in case you are worried that your parsed html content might cause you trouble with the values.
$(document).ready(function() {
$("#mytable").on('click', 'tr', onCellClick);
//Bind the event to the table row
function onCellClick() {
let row = $(this); //get the jquery Object for the row
let rowValues = {}; //An empty object to hold your data
let temp;
//extract the value of every cell in the row
//Doing it this way gives you flexibility on the amount of colums you have
row.find('td').each(function(item) {
temp = $(this);
rowValues[temp.data('column')] = temp.text();
//this could be changed to
//rowValues[temp.data('column')] = temp.data('value);
//if you desire to use a separate data-value property
});
console.log(rowValues);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width:100%" id="mytable">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td data-column="name" data-value="Jill">Jill</td> <!-Adding value property-->
<td data-column="lastname">Smith</td>
<td data-column="age">50</td>
</tr>
<tr>
<td data-column="name">Eve</td>
<td data-column="lastname">Jackson</td>
<td data-column="age">94</td>
</tr>
</table>
This is the first table on the page by the way. I want to be able to change the value of the td elements by referencing their position.
So, if I could state the 3rd td element in a specific table>tr pathway that would be great. And then to replace the text value. The text itself repeats a lot so I can't do a search for specific text values.
Also some of the td values are blank <td> </td>. And I would like to replace the blank table values as well. The tr class names are identical.
<table><tbody>
<tr class="table-header"><td colspan="4"><h3>First</h3></td></tr>
<tr class="table-header">
<th class="col">Number</th>
<th class="col">Name</th>
<th class="col">Quantity</th>
<th class="col">Type</th>
</tr>
<tr class="left-bottom-border">
<td>element 1</td>
<td>element3</td>
<td>element2</td>
<td>element3</td>
</tr>
<tr class="left-bottom-border">
<td>blah</td>
<td>blah</td>
<td>blah</td>
<td>blah</td>
</tr>
<tr class="left-bottom-border">
<td>stuff</td>
<td>stuff</td>
<td>stuff</td>
<td>blank</td>
</tr>
<tr class="left-bottom-border">
<td>I don't</td>
<td>think this matters</td>
<td>but I'm going to replace</td>
<td>all of the data</td>
</tr>
<tr class="table-header"><td colspan="4"><h3>Second Table</h3></td></tr>
<tr class="table-header">
<th class="col">Number</th>
<th class="col">Name</th>
<th class="col">Quantity</th>
<th class="col">Type</th>
</tr>
<tr class="left-bottom-border">
<td>More</td>
<td>x</td>
<td>x</td>
<td>x</td>
</tr>
<tr class="left-bottom-border">
<td>x</td>
<td>x</td>
<td>x</td>
<td>x</td>
</tr>
<tr class="table-header"><td colspan="4"><h3>Third Table</h3></td></tr>
<tr class="table-header">
<th class="col">Number</th>
<th class="col">Name</th>
<th class="col">Quantity</th>
<th class="col">Type</th>
</tr>
<tr class="left-bottom-border">
<td>element 1</td>
<td>element3</td>
<td>element2</td>
<td>element3</td>
</tr>
<tr class="left-bottom-border">
<td>so more elements</td>
<td>yada</td>
<td>yada</td>
<td>ya</td>
</tr>
<tr class="left-bottom-border">
<td>x</td>
<td>y</td>
<td>z</td>
<td>aa</td>
</tr>
</tbody></table>
Use document.querySelector()Doc to get the table, then use the .rowsDoc and .cellsDoc properties to get a particular <td> (or <th>) cell.
For example, for the code shown in the question, this will change the third row, first column ("element 1"):
var fstTable = document.querySelector ("body > table:nth-of-type(1)");
fstTable.rows[2].cells[0].textContent = "*changed*";
You can see this code in action at jsFiddle.
To find and replace blank cells, you could use the :empty selector with querySelectorAll -- except that this works poorly in practice due to stray whitespace.
The more robust alternative is to actually check the content of the cells. Like so:
var fstTable = document.querySelector ("body > table:nth-of-type(1)");
/*-- This only works when there is no stray whitespace:
var emptyCells = fstTable.querySelectorAll ("td:empty");
*/
var emptyCells = fstTable.querySelectorAll ("td");
for (var J = emptyCells.length - 1; J >= 0; --J) {
if (emptyCells[J].textContent.trim () == "") {
emptyCells[J].textContent = "*was blank*";
}
}
.trim() removes leading and trailing whitespace.
this javascript code let's you replace the content of a TD by it's index where 0 is the first element.
var tbl=document.getElementsByTagName("table")[0]; //get the first TABLE
var trs=tbl.getElementsByTagName('tr'); //get all TR's in that table
var replaceTD=function(TRindex,TDindex,value){
trs[TRindex].getElementsByTagName('td')[TDindex].innerHTML=value; // replaced with innerText
};
to change the second TD of the first TR that is not a title (so the third)
your indexes will be TRindex=2 cause it starts from 0 ...
and the TDindex=1
and the function you will call is :
replaceTD(2,1,'WHATEVER');