Please excuse me, my English is not very good.
I have a datatable array with each row of this form :
<tr id="1234">
<td id="td_mob_1234" colspan="2"> xxxxx </td>
<td id="td_desk_1234" style="display: none;"> yyyy </td>
<td>aaa</td>
<td>bbb</td>
</tr>
At some point, I need to edit all the rows in the table.
So I get the lines of the table.
I'm making my changes.
And I apply them that way.
var data = datatable.rows().data();
for (var i = 0, row; row = data[i]; i++) {
// I'm making my changes. on row[0], row[1].....
// apply
datatable.row(i).data(row).draw();
}
My problem is that row [0], row [1]…. contain only the inside of my td.
I would also need to access the attributes of my td, to change from colspan = 2 to colspan = 1 and from display: none to display: block for the second td.
How can I access and modify these attributes?
Thank you
I succeeded with cell().node() :
var cell = datatable.cell("#id").node();
$(cell).attr('colspan', 1);
var cell = datatable.cell("#id").node();
$( cell ).css( 'display', 'block' );
Thanks
Related
I would like to create one additional row in HTML Table which is very common and can be done if we have id or class available of that table.
But in my case I have one page which contains many forms and tables.
But in all those I have one form which contains only one element i.e table and I would like to create one more row and move few columns from 1st row to newly created row.
For this I have created simple HTML page.Please find below code and help me to achieve my output.
<h:form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</h:form>
Here Ia m getting output like
Item Info Description Product Keywords Documents Image Video
But I want to achieve something like below:
Item Info Description Product Keywords
NEW CELL1 Documents Image Video
means I would like to remove few columns from existing row and I would like to add it in newly created row.
For this I have written Javascript like:
<script type="text/javascript">
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.elements[0];
var tr = document.createElement("tr");
tr.id="row2";
table.appendChild(tr);
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
var col5 = document.getElementById("col5");
tr.appendChild(col5);
var col6 = document.getElementById("col6");
tr.appendChild(col6);
var col7 = document.getElementById("col7");
tr.appendChild(col7);
}
</script>
Here, My problem is this entire form will be generated automatically so I can't give the Id for the table and with this script it is not identifying my table when I am giving form.elemets[0];
I want to find table element so that I can create row in that table.
You can find the table by doing this:
Get one of the elements in a table row, and get the parent node until you've got the table. In this case you could do document.getElementById('col1').parentNode.parentNode
And just to ease things,
You can insert this string '</tr><tr>' in a row, after a table cell, to easily create a new row.
This should be better than document.getElementsByTagName('table'), because if you have lots of tables which are far away, it will take more time to find your table's index in that array.
Use getElementsByTagName to get the table from within your form, which has an ID
window.onload = function() {
split();
};
function split() {
var form = document.getElementById("myForm");
var table = form.getElementsByTagName("table")[0];
var tr = document.createElement("tr");
tr.id = "row2";
table.appendChild(tr);
var cell = tr.insertCell(0);
cell.innerHTML = "NEW CELL1";
/*Your original code produces duplicate IDs which is a BAD thing*/
var col5 = document.getElementById("col5");
/*Update new Id*/
col5.id += "_new";
tr.appendChild(col5);
var col6 = document.getElementById("col6");
/*Update new Id*/
col6.id += "_new";
tr.appendChild(col6);
var col7 = document.getElementById("col7");
/*Update new Id*/
col7.id += "_new";
tr.appendChild(col7);
}
<form id="myForm">
<table>
<tr>
<td id="col1">Item Info</td>
<td id="col2">Description</td>
<td id="col3">Product</td>
<td id="col4">Keywords</td>
<td id="col5">Documents</td>
<td id="col6">Image</td>
<td id="col7">Video</td>
</tr>
</table>
</form>
You also have a mismatch of column numbers, with the code provided you originally have 7 columns and only insert 4, this will produce inconsistent results, make sure to use the colspan attribute as needed.
You should be able to use JavaScript's querySelector method to select the table data you want to remove from the document.
Something like var rowToDeleteOrAddTo = document.querySelector("#myForm > table > tr > td"); should help you get there. You'll need to lookup CSS Selectors to get the specific selectors you need. You may need to use the textContent property once you have a node to make sure you are deleting the right one.
I have html table that looks like this:
| H1 |
H1 |-----------------|
| H2 | H2 |
------------------------|
Text |Number|Percentage|
------------------------|
Text |Number|Percentage|
------------------------|
...
Is there a way to add "Total" footer that will look like this:
| H1 |
H1 |-----------------|
| H2 | H2 |
------------------------|
Text |Number|Percentage|
------------------------|
Text |Number|Percentage|
------------------------|
...
------------------------|
Total:|Sum |Avg prcntg|
------------------------|
using JS, that will take into account class of a cell (percentage, number) and calculate total for columns accordingly?
There is a few somewhat similar solutions, but I'm new to JS (and HTML for that matter) and can't modify them myself. I would aslo greatly appreciate if you throw in some comments along the solution, so I could actually learn something :)
<table border="1">
<thead>
<th rowspan="2">Header</th>
<th colspan="2">Header</th>
<tr>
<th>Numbers</th>
<th>Percentages</th>
</tr>
</thead>
<tbody>
<tr>
<td>Text</td>
<td class="number">1</td>
<td class="percentage">30</td>
</tr>
<tr>
<td>Text</td>
<td class="number">2</td>
<td class="percentage">40</td>
</tr>
</tbody>
<tfoot>
<td>Total:</td>
<td class="result"></td>
<td class="result"></td>
</tfoot>
</table>
EDIT
Okay, I fiddled around with other solutions a bit more and here what I made:
var totals = [0, 0, 0, 0, 0];
var tbodyrows = $('#myTable tbody').find('tr').length;
$(document).ready(function() {
var $dataRows = $("#myTable tbody tr");
$dataRows.each(function() {
$(this).find('.number').each(function(i) {
totals[i] += parseInt($(this).text());
});
});
$("#myTable tfoot td:not(:first-child)").each(function(i) {
if ($(this).hasClass("result")) {
$(this).text(totals[i]);
}
if ($(this).hasClass("perresult")) {
$(this).text(totals[i] / tbodyrows);
}
});
});
JSFIDDLE
That works, but what if I want it to make footer, instead of populating premade one?
If you want to add the totals to the table yourself, you are likely looking for something like jQuery's .append function. This will let you add on new table rows to the end of the table, once you've calculated the totals. Link to docs: http://api.jquery.com/append/
// JavaScript: (comments below each line start with //)
var tableHtml = '';
// new empty string variable to put your table html in
tableHtml += '';
// this starts a new table row (tr), += adds more to the existing value
tableHtml += 'Text';
// this is the text column (cell)
tableHtml += ''+numberTotal+'';
// the js number variable in a new cell
tableHtml += ''+percentTotal+'';
// the js percent variable in a new cell
tableHtml += '';
// the end of a new table row
$( "table" ).append(tableHtml);
// appends this html as a child of "table" or "tbody" if that works better
You may need to use some of the other comments above to get the totals, but my answer shows how to add it to the table after the page is loaded in real time.
Yes it can be done.You can get the elements using jquery and run a loop to find the total and average percentage as follows:
var numbers=$('.number')
var percentage=$('.percentage')
var avg=0;
var total=0;
for(var i=0;i<numbers.length;i++){
total=total+parseInt(numbers.eq(i).text())
avg=avg+parseInt(percentage.eq(i).text())
}
$('.result').eq(0).text(total)
$('.result').eq(1).text(percentage/numbers.length)
I am trying to get the information from my table td's, using javascript. How can i achieve this? I have tried and failed, because i do not exactly understand the JS. So far, i have managed to get one of them to work, which is 'id' but thats just getting info from the db directly, the td values ive been unable to.
echoing the vals in my php update page shows the id val being passed successfully, but none others.
EDIT
Per your last comment I can recommend you use an event listener on all <td> tags and this way you can just get the relevant text of the specific <td> that the user clicked:
var tds = document.querySelectorAll('td');
for (var i = 0; i < tds.length; i++) {
var td = tds[i];
td.addEventListener('click', function(){
console.log(this.innerText)
});
}
<table>
<tr>
<td class="awb">I am the first awb</td>
<td class="awb">I am the second awb</td>
</tr>
<tr>
<td class="differentClass">I am the first differentClass</td>
<td class="differentClass">I am the second differentClass</td>
</tr>
</table>
You are approaching this all wrong...
Instead of this:
var awbno = String(tr.querySelector(".awb").innerHTML);
Do this:
var awbno = document.querySelector(".awb").innerHTML;
Here is a snippet:
var awbno = document.querySelector(".awb").innerHTML;
console.log(awbno);
<table>
<tr>
<td class="awb">Test Text inside a td tag</td>
</tr>
</table>
in order to get the contents of any element using class
let value = document.querySelector('.className').innerHTML;
in order to get the contents of a specific TD
let value = document.querySelector('td.className');
In my application i use a framework that generates a table with the id of the cells at Run-Time in ascending order.
So that i have "ElementX1X1" for row1 and column1, "ElementX1X2" for row1 and column2 etcetc...
The HTML structure generated will be:
<tr>
<td class="my_msg" align="left">
<id="ElementX1X1">
what i can set is the class(my_msg) and the content of the cell(of the table).
I want simply make:
var test=document.getElementById("ElementX1X1");
test.onclick=function();
but i'm not able to recognize the cell...
i want to make getElementById only if it is in the class "my_msg" or only if it has a certain content(as i said the only two things i can set)...
Anyone has any idea on how i can solve the problem?!
Thanks in advance!
Update the HTML to:
<td id="ElementX1X1" class="my_msg" >...
Edited - to work around broken framework:
<tr>
<td class="my_msg" align="left">
<id="ElementX1X1">
some content
</td>
<td class="my_msg" align="left">
<id="ElementX1X2">
some content
</td>
</tr>
If you want to find row 1 column 2, you can cheat using a bit of jQuery to inspect the contents of the element:
var row = 1;
var column = 2;
var matched = null;
$(".my_msg").each({
if($(this).html().indexOf('<id="ElementX' + row + 'X' + column + '">')!=-1){
matched = $(this);
}
});
matched will either point to the element you're looking for or null - but if you already know the row and column id's of the cells then why not just walk the DOM?
var row = 1;
var column = 2;
var matched = null;
var table = document.getElementsByTagName("TABLE")[0]; // up to you how your find it
try {
matched = table.getElementsByTagName("TR")[row-1].getElementsByTagName("TD")[column-1];
}
catch(err) {
// not found
}
Or the brute force way (i.e. fix the framework output):
var table = $("#tableid"); // up to you how your find it
table.html(table.html().replace(/">\n<id="/g,'" id="'));
your code is now:
<tr>
<td class="my_msg" align="left" id="ElementX1X1">…</td>
<td class="my_msg" align="left" id="ElementX1X2">…</td>
…
so you can use
$("#ElementX2X1");
to select the first row, second column
Neither is particularly elegant, but should get the job done while you wait for your buggy framework to be fixed ;)
I would like to hide the entire age column on this table.
<table id="displayTable">
<tr>
<td class="Name"></td>
<td class="Phone"></td>
<td class="Age"></td>
</tr>
</table>
Javascript follows to hide Age cell -
var table = document.getElementById('displayTable');
var tableRow = table.getElementsByTagName('tr');
for (var row = 0; row < tableRow.length; row++) {
var cells = tableRow[row].getElementsByTagName('td')
cells[2].style.display='none';
}
error says -
"2.style is null or not an object."
What am I missing?
Well, first of all, check your table id. You have it set to 'displayTable' but you're attempting to look it up by 'displayLossTable'.
When i fix that id, and plug your code into jsFiddle, everything works.
what does alert(cells[2]) give you? Alternatively you should try add/remove class instead of inline styles:
el.className+= 'hide'