Regular expression for deleting a column using javascript? - javascript

So my HTML table looks like this:
<table class="mon_list" id="mon_list">
<tr class='list'>
<th class="list" align="center"><b>Klasse(n)</b></th>
<th class="list" align="center">Stunde</th>
<th class="list" align="center">Fach</th>
<th class="list" align="center">Raum</th>
<th class="list" align="center">Vertretungs-Text</th>
<th class="list" align="center">Vertr-Text-2</th>
</tr>
<tr class='list odd'>
<td class="list" align="center" style="background-color: #FFFFFF"><b>6.1</b></td>
<td class="list" align="center" style="background-color: #FFFFFF">1 - 2</td>
<td class="list" align="center" style="background-color: #FFFFFF">Ku</td>
<td class="list" align="center" style="background-color: #FFFFFF">
<s>312</s>006</td>
<td class="list" align="center"> </td>
<td class="list" align="center"> </td>
</tr>
...
</table>
and I need to delete the last column. I cannot find a regular expression for that. I need to delete the 6th element in each row.

If you want to remove a column, you could loop through each row and remove the cell at the specific position (in this case the last one)
var table = document.getElementById("myTable");
for (var i = 0, row; row = table.rows[i]; i++) {
row.removeChild(row.cells[row.cells.length - 1]);
}
Let me know if that works

This can be read as an XY problem, that is "how do I do X using Y",
perhaps the question could be rephrased as, "how do I do X",
I think in this case Y is the "regular expression".
I also think your code could use better formatting, would you mind editing the question?
in JavaScript you can remove rows by using the DOM removeChild() API passing the ID of the column row like so:
var rows = document.getElementById("tableObj").querySelector("tr");
for(var i=0;i<rows.length;i++){
var cols = rows[i].querySelector("td");
for(var r=0;r<cols.length;r++){
if(r == 3){ //i.e. delete fourth column
rows[i].removeChild(cols[r]);
}
}
}

Related

Create array of non hidden td rows

So I have a table where the users can filter out specific rows, by checking a checkbox. If a checkbox is selected then, some rows will get the hidden state.
I want to create a array with all the rows that isn't hidden, but I can't seem to get the state of the <td>.
The tables id is ftp_table and the rows I need the data from has the class name download. I tried to so something like this, to get the visibility value, but without any luck. The function is triggered after a hide row function has run.
function download_log() {
var rows = document.getElementsByClassName("download");
var log = [];
for (var i = 0; i < rows.length; i++) {
// Check if item is hidden or not (create a if and push into array)
console.log(getComputedStyle(rows[i]).visibility);
// append new value to the array IF NOT HIDDEN
log.push(rows.item(i).innerHTML);
}
}
The output I get when i hide something is everything is visible?:
Here is a example of the table, where all info rows has been hidden:
<table class="ftp_table" id="ftp_table">
<tbody>
<tr class="grey">
<th>Log</th>
</tr>
<tr class="info" hidden>
<td class="download">2021-10-06 12:38:15.946 INFO [conftest:101] -------------- Global Fixture Setup Started --------------</td>
</tr>
<tr class="debug">
<td class="download">2021-10-06 12:38:16.009 DEBUG [Geni:37] Initializing</td>
</tr>
<tr class="info" hidden>
<td class="download">2021-10-06 12:38:16.059 INFO [Wrapper:21] Downloading</td>
</tr>
<tr class="info grey" hidden>
<td class="download">2021-10-06 12:38:16.061 INFO [Handler:55] AV+</td>
</tr>
<tr class="debug grey">
<td class="download">2021-10-06 12:38:16.063 DEBUG [Session:84] GET'</td>
</tr>
</tbody>
</table>
You could use the following selector :
document.querySelectorAll("#ftp_table tr:not([hidden]) td.download");
It will select the td.download elements in tr that are not hidden in your table.
var visibleTds = document.querySelectorAll("#ftp_table tr:not([hidden]) td.download");
var arr = [];
for(let i = 0; i < visibleTds.length; i++){
arr.push(visibleTds[i].innerText);
}
console.log(arr);
<table class="ftp_table" id="ftp_table">
<tbody>
<tr class="grey">
<th>Log</th>
</tr>
<tr class="info" hidden>
<td class="download">2021-10-06 12:38:15.946 INFO [conftest:101] -------------- Global Fixture Setup Started --------------</td>
</tr>
<tr class="debug">
<td class="download">2021-10-06 12:38:16.009 DEBUG [Geni:37] Initializing</td>
</tr>
<tr class="info" hidden>
<td class="download">2021-10-06 12:38:16.059 INFO [Wrapper:21] Downloading</td>
</tr>
<tr class="info grey" hidden>
<td class="download">2021-10-06 12:38:16.061 INFO [Handler:55] AV+</td>
</tr>
<tr class="debug grey">
<td class="download">2021-10-06 12:38:16.063 DEBUG [Session:84] GET'</td>
</tr>
</tbody>
</table>
Why don't you use classList instead of style props ?
Like :
rows[i].classList.contains("hidden")

Select 2 columns of an HTML table based on the first column selected

I have an HTML table with like 7 columns. When I select a column I want all the other columns to be hidden except the column next to the selected one. To be clear, only 2 columns need to be visible at a time - and those are the one selected and the one next to it. If there is a column to the right of the selected column, this one should be shown along with the selected column, if not (last column selected) the column to the left shall be shown along with the selected one.
I tried using loops but the problem is the user can select any column from the table.
My code:
var I = document.getElementsByTagName("th").length;
if(s=== I-1) { // s - index of selected column- check if its the last column
for (var D = 0; D < I-2; D++) {
var o = datatable.column(D);
o.visible(!o.visible());
}
} else {
for (var D = 0; D < s; D++) {
var o = datatable.column(D);
o.visible(!o.visible());
}
for (var D = s+1; D < I; D++) {
var o = datatable.column(D);
o.visible(!o.visible());
}
}
My HTML:
<table id="DataTables_Table_0" >
<thead>
<tr role="row" style="height: 0px;">
<th>
<div>Pro</div>
</th>
<th>
<div>Pri</div>
</th>
<th>
<div>State</div>
</th>
<th>
<div>phyId</div>
</th>
<th>
<div>Title</div>
</th>
<th>
<div>Origin</div>
</th>
<th>
<div>type</div>
</th>
</tr>
</thead>
<tbody style="">
<tr role="row" class="odd">
<td class="0 sorting_1">Private</td>
<td class="1">High</td>
<td class="2">Create</td>
<td class="3">E210DC29509F</td>
<td class="4">5</td>
<td class="5">8/9/2019, 8:24:00 AM</td>
<td class="6">Issue</td>
</tr>
<tr role="row" class="even">
<td class="0 sorting_1">Public</td>
<td class="1">Low</td>
<td class="2">Assign</td>
<td class="3">E210DC29509F</td>
<td class="4">5</td>
<td class="5">8/9/2019, 9:11:11 AM</td>
<td class="6">Issue</td>
</tr>
<tr role="row" class="odd">
<td class="0 sorting_1">Private</td>
<td class="1">Medium</td>
<td class="2">Assign</td>
<td class="3">E210DC29509F</td>
<td class="4">5</td>
<td class="5">8/9/2019, 9:17:26 AM</td>
<td class="6">Issue</td>
</tr>
<tr role="row" class="even">
<td class="0 sorting_1">Public</td>
<td class="1">Urgent</td>
<td class="2">Active</td>
<td class="3">E210DC29509F</td>
<td class="4">5</td>
<td class="5">8/8/2019, 4:14:59 PM</td>
<td class="6">Issue</td>
</tr>
</tbody>
</table>
An update to the question: I can select the 1st column always alonwith the column selected by the user. So that means I dont have to manually select the adjacent column from the table. I just modified the code:
for (var D = 1; D < I/2 ; D++) {
if (D !== s ) {
var o = f.datatable.column(D);
o.visible(!o.visible());
}
}
Now it works as expected. Actually this was for generating a line chart for the table data. Now i get a line chart, but i am just confused as to if the line chart does look as expected. I mean I have attached a screenshot of my line chart, but it looks like ther is something more to do. Sorry for not mentioning about the line chart as i thought it would make the question more complicated and confusing.linechart tabledata for the line chart
How exactly should a line chart look with my table.
I would make those td class names more explicit, so they're clearly labeling columns (like col-0), and then query the DOM based on those.
On selection change:
Hide all the columns.
Get the index being selected.
Calculate the two column class names to show.
Query for those class names and show those DOM nodes.
Here's some (untested) example js:
$('th, td').hide();
// for the OP: make sure colIndex isn't the rightmost col
const selectedCol = 'col-' + colIndex;
const nextCol = 'col-' + (colIndex + 1);
$('.' + selectedCol).show();
$('.' + nextCol).show();
Get the count of all columns.
then hide all the columns.
and then only show the selected and next or previous column
var I = document.getElementsByTagName("th").length;
function hideCol(s){
datatable.columns( 'th' ).visible( false );
if(s == I-1){
datatable.column(s).visible(true);
datatable.column(s-1).visible(true);
}else if(s < I){
datatable.column(s).visible(true);
datatable.column(s+1).visible(true);
}
}
hideCol(2);

Javascript Checkbox From a Table Returning Undefined

When I run the following code the alert comes back as 'undefined' when I would like is to return True or False depending on if the checkbox is check at the time that the user triggers the JavaScript to run.
The user is triggering it with a button. Currently when the user presses the button the script returns a 'undefined' for each row of the table.
Eventually I would like to create a JavaScript array that I will pass back to the server with an Ajax call but this is of little use if I can cannot determine the state of the check boxes for every row of the table.
Also, I'm using Jinja2 templating which explains the curly brackets but this should be of little consequence because the table is being created without issue when the HTML renders.
var table = document.getElementById("filterTable");
for (var i=1; i<table.rows.length; i++){
var isChecked = (table.rows[i].cells[2].checked);
alert(isChecked);
My table looks like this:
<table class="table table-condensed table hover" id = "filterTable">
<thead>
<tr>
<th>Origin</th>
<th>Destination</th>
<th>Active</th>
</tr>
</thead>
<tbody>
{% for dep in dependencies %}
<tr class="row">
<td><p>{{dep.origin}}</p></td>
<td><p>{{dep.destination}}</p></td>
<td>
<input type="checkbox" value="isSelected"/>
</td>
</tr>
{% endfor %}
</tbody>
</table>
The checkbox is the first child of td not the td itself (cells[2] returns third td) so checked property of td element would be always undefined.
You can get the checkbox from children property.
var isChecked = table.rows[i].cells[2].children[0].checked;
var table = document.getElementById("filterTable");
for (var i = 1; i < table.rows.length; i++) {
var isChecked = (table.rows[i].cells[2].children[0].checked);
alert(isChecked);
}
<table id="filterTable">
<thead>
<tr>
<th>Origin</th>
<th>Destination</th>
<th>Active</th>
</tr>
</thead>
<tbody>
<tr class="row">
<td>
<p>{{dep.origin}}</p>
</td>
<td>
<p>{{dep.destination}}</p>
</td>
<td>
<input type="checkbox" value="isSelected" />
</td>
</tr>
</tbody>
</table>
In case there are other elements as the child then you can get it using querySelector() method with attribute equals selector.
var isChecked = table.rows[i].cells[2].querySelector('[type="checkbox"]').checked;
var table = document.getElementById("filterTable");
for (var i = 1; i < table.rows.length; i++) {
var isChecked = (table.rows[i].cells[2].querySelector('[type="checkbox"]').checked);
alert(isChecked);
}
<table id="filterTable">
<thead>
<tr>
<th>Origin</th>
<th>Destination</th>
<th>Active</th>
</tr>
</thead>
<tbody>
<tr class="row">
<td>
<p>{{dep.origin}}</p>
</td>
<td>
<p>{{dep.destination}}</p>
</td>
<td>
<input type="checkbox" value="isSelected" />
</td>
</tr>
</tbody>
</table>
table.rows[i].cells[2] only find the td that contains the checkbox.
You need to query for the checkbox before you check the property.
var td = table.rows[i].cells[2];
var checkbox = td..querySelector('input[type="checkbox"]');
var isChecked = checkbox.checked;

Change background-color of 1st row in the table

Below is my table that is getting populated with spry dataset
Here is my dataset
var ds1 = new Spry.Data.XMLDataSet("/xml/data.xml", "rows/row");
Here is my jquery inside a method that is called on a button click
function addRow()
{
var newRow = new Array();
var nextID = ds1.getRowCount();
newRow['ds_RowID'] = nextID;
newRow['id'] = "x";
newRow['name'] = "Abhishek";
newRow['country'] = "India";
ds1.dataHash[newRow['ds_RowID']] = newRow;
ds1.data.push(newRow);
Spry.Data.updateRegion(ds1);
ds1.sort('name','descending');
ds1.setCurrentRow(newRow.ds_RowID);
$(".trEven td").css("background-color", "red");
alert($.fn.jquery);
/*$("#tableDg tbody tr:first").css({
"background-color": "red"
});*/
}
Here is my table
<div id="cdiv" style="width:100%;" spry:region="ds1">
<table id="tableDg"
style="border:#2F5882 1px solid;width:100%;" cellspacing="1" cellpadding="1">
<thead>
<tr id="trHead" style="color :#FFFFFF;background-color: #8EA4BB">
<th width="2%"><input id="chkbHead" type='checkbox' /></th>
<th width="10%" align="center" spry:sort="name"><b>Name</b></th>
<th width="22%" align="center" spry:sort="host"><b>Country</b></th>
</tr>
</thead>
<tbody spry:repeat="ds1">
<tr id="trOdd"
spry:if="({ds_RowNumber} % 2) != 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #FFFFFF" class="{ds_OddRow}">
<td><input type="checkbox" id="chkbTest" class = "chkbCsm"></input></td>
<td width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {country}</td>
</tr>
<tr id="trEven"
spry:if="({ds_RowNumber} % 2) == 0" onclick="ds1.setCurrentRow('{ds_RowID}');"
style="color :#2F5882;background-color: #EDF1F5;" class="{ds_EvenRow}">
<td><input type="checkbox" class = "chkbCsm"></input></td>
<td id="tdname" width="10%" align="center"> {name}</td>
<td width="22%" align="center"> {country}</td>
</tr>
</tbody>
</table>
</div>
Am I going wrong somewhere, please guide me. Thanks :)
If I remember right, <tr> is only describing structure. <td> represents visual part of the table. Or this is how some browsers renders them.
Therefore $("#trEven td").css("background-color", "red") should work. And preferrably you should use classes instead of ids in these kind of cases where there may exist multiple instances.
Works for me (jsFiddle). What problems are you experiencing?
If your use classes instead of id's, you can use something like the following:
$('.trEven').each(function() {
$(this).css({"background-color": "red"});
});
See for reference: jQuery API - .each()
You shouldn’t be using ids for odd and even rows. id values are meant to be unique within the page.
So, I’d suggest:
<tr class="trOdd"
and:
<tr class="trEven"
and then:
$(".trEven")
If you really only want the first row in the table body to get a red background (as opposed to all the even ones), then your selector should be:
$("#tableDg tbody tr:first")

How to iterate over table and define class for tds of trs?

I have a table like that:
<table id="myTable" cellspacing="0" cellpadding="10" border="0" width="100%">
<tbody>
....
<tr style="color: blue;" id="bankRecord377">
<td align="center" class="styleOdd"> <input type="checkbox" value="377" name="377"></td>
<td align="center" class="styleOdd">377</td>
<td align="center" class="styleOdd"></td>
<td align="center" class="styleOdd">391</td>
</tr>
....
<tr style="color: blue;" id="bankRecord386">
<td align="center" class="styleEven"> <input type="checkbox" value="386" name="386"></td>
<td align="center" class="styleEven">386</td>
<td align="center" class="styleEven"></td>
<td align="center" class="styleEven">396</td>
</tr>
...
<tr style="color: blue;" id="bankRecord322">
<td align="center" class="styleEven"> <input type="checkbox" value="322" name="386"></td>
<td align="center" class="styleEven">322</td>
<td align="center" class="styleEven"></td>
<td align="center" class="styleEven">314</td>
</tr>
...
</tbody>
</table>
class="styleOdd" makes row gray background class="styleEven" makes row background blue. I iterate over that table with Struts2 and define classes but user can remove some of table rows when he sees that HTML file. If user remove one of the table row, e.x. :
<tr style="color: blue;" id="bankRecord386">
...
</tr>
Colors of background was gray, blue, gray. However it is gray, gray now(because user removed a tr which includes classEven tds).
All in all what I want is iterate over that table again and defining classes styleOdd, styleEven, styleOdd, styleEven... again.
How can I do it with JavaScript or JQuery?
PS: I want to it for my table(which has id=myTable)'s every tds of trs.
EDIT: I want it except for the first tr(and it's tds).
You can use :even and :odd, but then you would iterate over the table rows twice. That might lead to unacceptable performance if your table has many rows.
I'd suggest using each() instead:
$("#myTable tr").each(function(index, row) {
var $cells = $("td", row);
if (index & 1) {
// Odd.
$cells.removeClass("styleEven").addClass("styleOdd");
} else {
// Even.
$cells.removeClass("styleOdd").addClass("styleEven");
}
});
You can use the :odd selector to target odd rows. (there is also a :even selector)
$('.td:odd').class('odd');
Trigger this when removing a row from the table to update classes.
There are also both CSS Selector but not widely supported.
$('#myTable tr:odd td').toggleClass('styleOdd', true).toggleClass('styleEven', false);
$('#myTable tr:even td').toggleClass('styleOdd', false).toggleClass('styleEven', true);
I believe you could also do it automatically using CSS. Although it requires a fairly modern browser.
Updated to take into account the table ID

Categories

Resources