Access to cell attributes with row id - javascript

I have the following table and jQuery code to create an object based on some columns/cells data-attributes:
<tbody>
<tr id="1">
<td data-name1="Name 1">Name 1</td>
<td data-name2="Name 2">Name 2</td>
<td data-name3="Name 3">Name 3</td>
</tr>
<tr id="2">
<td data-name1="Name 1">Name 1</td>
<td data-name2="Name 2">Name 2</td>
<td data-name3="Name 3">Name 3</td>
</tr>
</tbody>
Right now I have stored all the tr id's in a variable so I have this jQuery code:
for (var x = 0; x < idsVar.length; x++) {
var tdName1 = $(`#${idsVar[x]} > td`).attr('data-name1');
var tdName2 = $(`#${idsVar[x]} > td`).attr('data-name2');
}
This code seems to work. The problem is that now I'm implementing jQuery DataTables library with default pagination and the problem I'm facing is that for example; if my table contains more than 1 page the above code only works for the rows on the current page, if I want to access to the rows from other page they doesn't exists for my jQuery code.
I was reading the DataTables documentation and seems that this code could help:
var table = $('#example').DataTable();
table.rows().nodes().etc...
But I think that code loops throught all the table rows and what I'm trying to do is only on some specific row ids. So my question is how can I access to a specific row id and some data attributes. Maybe something like:
table.rows('specificId').nodes('data-attribute')
or
table.rows('specificId').nodes().something to get the data attribute

To access to a specific row by its ID you can use this:
var row = table.row('#idHere')
And for access to the data attributes of that row you can use this:
var row = table.row('#idHere').nodes()[0];
$(row).attr('data-attributeName');
Please go to datatable docs for more information.

Related

How to change text in table column using javascript

I have this code in my website is there any way to change text inside (td) tag in table using javascript
<div id="mvctable">
<table width="100%">
<tbody>
<tr>
<td style="font-size:2; text-align:Right;color:#ffffff;">
<img src="https://babilsport.com/wp-content/plugins/mechanic-visitor-counter/counter/mvcvisit.png"> Visit Today : 1
</td>
</tr>
<tr>
<td style="font-size:2; text-align:Right;color:#ffffff;">
<img src="https://babilsport.com/wp-content/plugins/mechanic-visitor-counter/counter/mvcmonth.png"> This Month : 1
</td>
</tr>
<tr>
<td style="font-size:2; text-align:Right;color:#ffffff;">
<img src="https://babilsport.com/wp-content/plugins/mechanic-visitor-counter/counter/mvctotal.png"> Total Visit : 1
</td>
</tr>
</tbody>
</table>
</div>
You need to find the td node you want to change via javascript. The most direct is to add an unique id attribute to the td you want to edit. Then use .textContent to set it.
document.getElementById("uniqueIdHere").textContent="newtext";
If you can't add unique ids then you will need to find via a known position or via the existing text in the td tag.
firstTD = document.getElementById("mvctable").querySelector('td');
firstTD.textContent="newtext";
You could get all of the TDs and loop through
tdElements = document.getElementById("mvctable").getElementsByTag('td');
for(var i = 0; i < tdElements.length; i++){
//do something to each td like
tdElements[i].textContent = "something new...";
}
Need more info to give you more details.

Load HTML content in a newly created table row

I've got a web page of very neatly structured data. There are about 20 "parents" and about 1000 "children". Right now I show a huge table of all the children. What I want to do is display the table of parents, and have a button/toggle for each row that when clicked would:
add a row beneath that parent in the table
execute a GET request to display an HTML table of children in that row
on the next click the button/toggle would remove that row from the table
My HTML looks like this:
<table id="tableofparents">
<tr>
<th>Buttons</th>
<th>Col B</th>
<th>Col C</th>
</tr>
<tr class="adder" id="101">
<td id="101" class="toggleChildren">Button</td> # unique id per row already exists
<td>Info Field 1</td>
<td>Info Field 2</td>
</tr>
<tr class="adder" id="202">
<td id="202" class="toggleChildren">Button</td>
<td>Info Field 1</td>
<td>Info Field 2</td>
</tr>
</table>
I figured out the code to toggle creation/deletion of a new table row here from here - Toggle between the creation and destruction of a table row jquery
<script type="text/javascript">
$(document).ready(function()
{
$('#tableofparents').on('click', ".toggleChildren", function () {
var thisRow = $(this).parents('tr.adder');
var hasNextRow = thisRow.next('tr.added').length;
if (hasNextRow) {
thisRow.next('tr.added').remove();
} else {
$(this).parents('tr.adder').after('<tr class="added"><td colspan="3" >This is where I want to load the HTML of the children via a GET request</td></tr>');
}
});
}
</script>
When I click on the button in the first row, it now toggles the addition of a new table row. But I also need that same click to execute a GET request to http://example.com/childdata?id=101 and load the HTML from that request into the new row, and I just can't figure out how to do that.
Is there a way to load HTML into the newly created row?
In your else statement you can do this:
var parent = $(this).parents('tr.adder'), id = parent.attr('id');
$.get('http://example.com/childdata?id='+id, function(html) {
parent.after('<tr class="added"><td colspan="3" >'+html+'</td></tr>');
});
I hope this will help you.

get the content of one column of each row in the table and then loop on each content

I have a table structure like this (refer below)
<table>
<thead>
<tr><th>id</th><th>name</th><th>address</th></tr>
</thead>
<tbody>
<tr rowid="1">
<td class="columnid">1</td><td class="columnname">name 1</td><td class="columnaddress">address 1</td>
</tr>
<tr rowid="2">
<td class="columnid">2</td><td class="columnname">name 2</td><td class="columnaddress">address 2</td>
</tr>
<tr rowid="3">
<td class="columnid">3</td><td class="columnname">name 3</td><td class="columnaddress">address 3</td>
</tr>
</tbody>
</table>
Now, I want to get the content from each table row that has attr('columnid') and loop each of it. So the code structure would look like this (refer below)
//We have 3 row, get all present rowid (1,2,3)
//count all the row that has rowid attribute
var rowcount = attr('rowid').length();
var i;
for (i = 0; i < rowcount; i++) //I dont know how to make it but assume in this for statement, I have stored the content from each rowid attribute {
//alert each rowid here
}
how to make it? any help, suggestions, recommendations, ideas, clues would be greatly appreciated. Thank you.
You can use tr[rowid] which will find all tr elements with rowid attribute, then use .has() to filter out trs which do not have td with class columnid like
$('tr[rowid]').has('td.columnid').each(function(){
alert($(this).attr('rowid'))
});
Demo: Fiddle
This code will scan all the td's with class columnidand alert the rowid of the row containing it. I hope this is what you want you code to do.
$("tr td.columnid").each(function(){
alert($(this).parent().attr("rowid"));
});
Fiddle

Set colspan/rowspan for a cell

I have a table and I want to change colspan/rowspan property of a cell on runtime. Here is an example:
<html>
<head>
<script type="text/javascript">
function setColSpan() {
document.getElementById('myTable').rows[0].cells[0].colSpan = 2
}
</script>
</head>
<body>
<table id="myTable" border="1">
<tr>
<td>cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
</table>
<form>
<input type="button" onclick="setColSpan()" value="Change colspan">
</form>
</body>
</html>
My problem is that the cells shift. Am I supposed to remove the cells over which the cell in question spans?
I can I do without removing?
I want to implement a simple spreadsheet. For now I managed to be able to select a rectangular range of cells and show a menu with a "Merge selected cells" option. I would like to be able to "unmerge" cells, so it would be good to span cells without having to remove other cells.
I think you need to delete the cell. Check with following code. What i did was removed the entire row and added new row with new column span
function setColSpan() {
var table = document.getElementById('myTable');
table.deleteRow(0);
var row = table.insertRow(0);
var cell = row.insertCell(0);
cell.innerHTML= "cell 1"
cell.colSpan = 2
}
The cells shift because that's what you're telling it to do. You're defining a table like this:
<tr>
<td colspan="2">cell 1</td>
<td>cell 2</td>
</tr>
<tr>
<td>cell 3</td>
<td>cell 4</td>
</tr>
So the shift you're seeing is what I would expect.
If you want to merge cells, you would have to take the contents of all the merged cells, concat them into a single cell, and remove the rest. For the trivial example, it'd go like this:
function setColSpan() {
var myTable = document.getElementById('myTable');
var cell2html = myTable.rows[0].cells[1].innerHTML;
myTable.rows[0].deleteCell(1);
myTable.rows[0].cells[0].innerHTML = myTable.rows[0].cells[0].innerHTML + ' ' + cell2html;
myTable.rows[0].cells[0].colSpan = 2;
}
However a more robust solution is...kind of complicated. Especially if you want the ability to unmerge. You'd have to preserve the information of the old cell structure somehow...possibly with putting something like <span class="oldCell">cell 2</span> around merged data? And then checking for the existence of "oldCell" spans when unmerging? But then you would have to preserve that information through user edits. And figure out what that means for merging across rows and columns. And also figure out what that means for overlapping merges.

Remove tables from HTML using jQuery

I've got many chunks of HTML coming into my app which I have no control over. They contain tables for layout, which I want to get rid of. They can be complex and nested.
What I want is to basically extract the HTML content from the tables, so that I can inject that into other templates in the app.
I can use jQuery or plain JS only, no server side trickery.
Does anyone know of a jQuery plugin of good tip that will do the job?
Littm - I mean to extract content from the td tags essentially. I want no trace of table left in the code when it's done. Thanks!
Here's an example of the type of HTML in question. It all comes in via XHR from some ancient application so I have no control over the markup. What I want is to get rid of the tables completely, leaving just the rest of the HTML or other text content.
<table>
<tr><td colspan="4"></td></tr>
<tr>
<td width="1%"></td>
<td width="40%" style="padding-left: 15px">
<p>Your access level: <span>Total</span></p>
</td>
<td width="5%">
<table><tr><td><b>Please note</b></td></tr></table>
</td>
<td width="45%" style="padding-left: 6px" valign="top"><p>your account</p></td>
</tr>
<tr><td colspan="4"> </td></tr>
<tr>
<td width="1%"></td>
<td width="40%" style="padding-left: 15px">
<table>
<tr>
<td align="right">Sort Code: </td>
<td align="center"><strong>22-98-21</strong></td>
</tr>
<tr>
<td align="right">Account Number: </td>
<td><strong>1234959</strong></td>
</tr>
</table>
</td>
<td width="5%"></td>
<td width="45%" style="padding-left: 6px">Your account details for</td>
</tr>
</table>
I've tried;
var data = ""
$("td").each(function(){
data += $(this).html()
});
$("article").append(data);
$("table").remove();
But var data still contains nested td tags. I'm no JS expert so I'm not sure what else to try....
Let's suppose that you have X number of tables.
In order to extract all the content information from these, you could try something like this:
// Array containing all the tables' contents
var content = [];
// For each table...
$("table").each(function() {
// Variable for a table
var tb = [];
$(this).find('tr').each(function() {
// Variable for a row
var tr = [];
$(this).find('td').each(function() {
// We push <td> 's content
tr.push($(this).html());
});
// We push the row's content
tb.push(tr);
});
// We push the table's content
content.push(tb);
});
So for instance, if we have the following 2 tables:
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
</tr>
</table>
<table>
<tr>
<td>r1</td>
<td>r2</td>
<td>r3</td>
</tr>
<tr>
<td>rA</td>
<td>rB</td>
</tr>
<tr>
<td>rP</td>
</tr>
</table>
The array content will be something like this:
content = [ [ [1, 2], [A] ] ] , [ [r1, r2, r3], [rA, rB], [rP] ] ]
\_______________/ \______________________________/
1st table 2nd table
and if you want to access the first table, you'll just have to access content[0] for instance.
Now, let's suppose that you have a DIV, with and id my_div, and that you want to output some table content in it.
For example, let's suppose that you only want to have the 1st table only. Then, you would do something like this:
// Note: content[0] = [[1, 2], [A]]
var to_print = "<table>";
for(var i=0; i<content[0].length; i++) {
to_print += "<tr>";
for(var j=0; j<content[0][i].length; j++)
to_print += "<td>"+ content[0][i][j] +"</td>";
to_print += "</tr>";
}
to_print += "</table>";
$("#my_div").html(to_print);
which will give you something like this:
<div id="my_div">
<table>
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>A</td>
</tr>
</table>
</div>
Hope this helps.
Edit: You should create a recursive function to do that.
Simply create you function that gets "td"'s as a value:
function searchTexts(td) {
if (td.find("td")) {
searchTexts(td.find("td"));
}
td.each(function(){
data += $(this).html()
$(this).remove(); // remove it for avoiding duplicates
});
}
Then call it passing a jQuery object to the function.

Categories

Resources