I want to hide/show table columns
using classes on columns,
without adding classes to each <td>
Table sample:
<table id="huge-table" border="1">
<caption>A huge table</caption>
<colgroup>
<col class="table-0">
<col class="table-0">
<col class="table-1">
<col class="table-1">
</colgroup>
<thead>
<tr>
<th>h1</th>
<th>h2</th>
<th>h3</th>
<th>h4</th>
</tr>
</thead>
<tbody>
<tr>
<td>1,1</td>
<td>1,2</td>
<td>1,3</td>
<td>1,4</td>
</tr>
<tr>
<td>2,1</td>
<td>2,2</td>
<td>2,3</td>
<td>2,4</td>
</tr>
</tbody>
</table>
Unfortunately $(".table-1").hide() doesn't work.
So I would like to get columns indexes by class and to use them with the nth-child selector:
indexes = getColumnIndexesByClass("table-1");
for ( var i=0; i<indexes.length; i++ ) {
$('#huge-table td:nth-child(indexes[i])').hide();
}
How can I implement the getColumnIndexesByClass function or any other equivalent solution?
EDIT
The table size is not known. I know only the classes.
Try this (using a slightly modified version of Raynos' function) and check out the demo:
function getColumnIndexesByClass(class) {
return $("." + class).map(function() {
return $(this).index() + 1; // add one because nth-child is not zero based
}).get();
}
var indexes = getColumnIndexesByClass('table-1'),
table = $('#huge-table');
for ( var i=0; i<indexes.length; i++ ) {
table.find('td:nth-child(' + indexes[i] + '), th:nth-child(' + indexes[i] + ')').hide();
}
function getColumnIndexesByClass(class) {
return $("." + class).map(function() {
return $(this).index();
}).get();
}
This function returns an array of numbers. I.e.
getColumnIndexesByClass("table-1") === [2,3]
$.each(getColumnIndexesByClass("page-1"), function(key, val) {
$("#hugetable td").filter(function() {
return $(this).index() === val;
}).hide();
});
The above will get all your tds and filter them to only tds in a particular index. Then hide those.
You may want to do more caching / optimisation.
In jQuery you can use $('.table-0').index() to find the position of the first matched element in relation to its siblings.
The full example would be:
var classname = 'table-0';
var indices = $('.'+classname).map(function() {return $(this).index()+1}).get();
$.each(indices, function(iter, val) {
$('td:nth-child('+val+'), th:nth-child('+val+')', '#huge-table').hide();
});
This also hides the headers. Note that in :nth-child count starts from 1. You could also have this in a single line, but it would look more ugly. You may also want to define a function for selecting indexes, but currently the code is only 3-5 lines long (given that you already have the class name) and is quite readable.
Read here for details about the index method: http://api.jquery.com/index
Edited: selects multiple columns with the same class, uses context.
Related
I have an array of objects being displayed in a table... My goal is to access a specific item within the array by clicking on that item in the table. I would then be able to add/remove classes and access the values, which is ultimately what I need to do.
Here's where I'm stuck...
myArray.forEach((item, index) => {
// Sort through array, render to DOM
document.getElementById('myElementID').innerHTML +=
'<tr>' +
'<td>' +
item.thing +
'</td>' +
'<td' +
item.thing2 +
'</td>' +
'</tr>';
// Completely stuck... I've added an event listener to each table row.
addEventListener('dblclick', () => {
console.log(//I want to log the index of the item I just clicked on);
});
});
Please forgive me if this is very easy or I'm going about this all wrong, but I'm very new to all of this and I haven't been able to structure my question in such a way that google is helpful.
Thanks in advance.
EDIT - Some html as requested...
<table id="myElementID">
<tr>
<th id="heading">Heading1</th>
<th id="anotherHeading">Heading2</th>
</tr>
</table>
EDIT again (sorry) ... and a JS fiddle. You'll see that it logs both indexes, instead of just the one I clicked on. https://jsfiddle.net/c4pd5wmg/4/
Instead of messing with index etc.. you can attach the event handler to the tr and just reference e.target in the event handler. I also cleaned up your adding of tr.
const myArray= [{number: 45,otherNumber: 55},{number: 48,otherNumber:58}]
myArray.forEach((item, index) => {
let row = document.createElement("tr");
let cell = document.createElement("td");
cell.innerHTML = item.number;
row.appendChild(cell);
cell = document.createElement("td");
cell.innerHTML = item.otherNumber;
row.appendChild(cell);
document.getElementById('myElementID').appendChild(row);
row.addEventListener('dblclick', (e) => {
console.log(e.target);
});
});
<table id="myElementID">
<tr>
<th id="heading">Heading1</th>
<th id="anotherHeading">Heading2</th>
</tr>
</table>
I have a html table
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
data here <3 ....
</tbody>
</table>
and here is my php (sample.php)
<?php
Query Code here..
Query Code there..
and so on
//this is the way I populate a table
while (query rows) {
echo '<tr>';
echo '<td>Sample Data</td>';
echo '</tr>;
}
?>
So to make this work and to populate the table this is what I do.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
<?php
include 'folder_location/sample.php';
?>
</tbody>
</table>
Disregard the image of the ouput but when I go to Inspect Element or even Ctrl + u I will see my table structure now is like this.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
<tr>
<td>Sample Data</td>
</tr>
</tbody>
</table>
Now here is the thing. I do not do that this is what I do.
$("#rpttable tr").remove();
for (i = 0; i < data.length; i++) {
tr = $("<tr />");
for (x in data[i]) {
td = $("<td />");
td.html(data[i][x]);
tr.append(td);
}
rpttable.append(tr);
}
Same output It does populate the table but when I go to Inspect Element or even Ctrl + u the output is.
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
**This is the part missing**
</tbody>
</table>
My question here is how can I literaly create an element usung javascript/ajax? same output in php. I mean write the element.
** Updated **
I am trying to run a css class from an external file and If I manualy edit it to suits my needs I will a long hour and also Its hard for me to explain its a class for table. I tried to use that class using default value in <table>. You know manualy write it at the back end. now Im trying to populate it using a php and ajax so, so far so good it does populate but when I try to run the class the class does not work.
TYSM
Using jquery you can add html rows to the tbody using:
$("#rptbody").html("<tr><td>value</td></tr>");
Is this what you want to do?
You can use JQuery append() method:
$('#rptbody').append('<tr><td>my data</td><td>more data</td></tr>');
In case you need to insert after last row:
$('#rptbody> tbody:last-child').append('<tr>...</tr><tr>...</tr>');
for (i = 0; i < 5; i++) {
let tr = $("<tr />");
for (j=0; j < 5;j++)
tr.append($("<td />",{html:j,class:"tbl"}));
$("tbody").append(tr);
}
.tbl{border:1px solid pink;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody></tbody>
</table>
You have asked roughly two questions. Let's break it down.
My question here is how can I literaly create an element usung javascript/ajax?
You are already doing this with your Javascript (client-side) code. It looks like you're using jQuery syntax, so we'll stick with that. This does create an element and inserts it into the page.
var $el = $("<div>I'm a new div element</div>");
$('body').append( $el );
This creates a new element, assigns it to the $el variable, and then appends it to the body of the page. This will not show up in "View Page Source" view, however. Why? Because this modifies the DOM -- the Dynamic Object Model.
To see this new element, you'll either need to look at the rendered output (what the user/you sees), or open up your browser's DevTools (often <F12>, or right-click -> inspect). In the DevTools, find the "Inspector" tab (or equivalent), then look for your new element in this live view of the DOM.
... same output in php.
In short, you can't. What Ctrl+U / View Page Source shows is the page as it was initially received from the server. This would be the exact content you would see if you were to use a command line tool, like curl or wget:
curl http://url.to.your.com/page
Since you include 'folder_location/sample.php' at the server, this is included in the page before the browser sees it. For your edification, I would consider reading up on the DOM.
Wikipedia
W3
Try this:
$("#rpttable tbody tr").remove();
var content = '' ;
for (i = 0; i < data.length; i++) {
content += "<tr>" ;
for (x in data[i]) {
content += "<td>" + data[i][x] + "</td>" ;
}
content += "</tr>" ;
}
$("#rpttable tbody").html(content) ;
Updated
I am using Google Chrome too. Please try the below code, and check the inspect element each time you add a new row. You can see the html in the Inspect Element changing!
function AppendNewRowToTable() {
var trLen = $("table tbody tr").length ;
var content = "" ;
content += "<tr>" ;
for (i = 0; i < 5; i++) {
content += "<td>" + trLen + "-" + i + "</td>" ;
}
content += "</tr>" ;
$("table tbody").append(content) ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Add new Row
<br />
<table>
<thead>
<tr>
<th>Title 01</th>
<th>Title 02</th>
<th>Title 03</th>
<th>Title 04</th>
<th>Title 05</th>
</tr>
</thead>
<tbody></tbody>
</table>
It seems your intent is to append extra rows to the table in your html response generated from your PHP script.
For that you don't need to clear all existing rows.
$("#rpttable tr").remove();
Build an array of rows and append once to your table body.
var $tbody = $('#rptbody');
var tableRowAdditions = [];
for (var i = 0; i < data.length; i++) {
var $tr = $("<tr></tr>");
for (var x in data[i]) {
var $td = $("<td></td>");
$td.html(data[i][x]);
$tr.append(td);
}
tableRowAdditions.push(tr);
}
$tbody.append(tableRowAdditions);
For a "pure" JavaScript approach, you can create elements using the createElement Web API
For example:
A paragraph with text "Hello" would be
var container = document.getElementById('rptbody');
var hello = document.createTextNode('Hello');
var helloParagraph = Document.createElement('p');
// Add text to paragraph
helloParagraph.appendChild(hello);
// Append to container
container.appendChild(helloParagraph);
The best way to create elements using jQuery is to use the following format:
// Create the TR and TD elements as jQuery objects.
var tr = $("<tr></tr>", {
"id":"tr1",
"class":"tr"
});
var td = $("<td></td>", {
"id":"td1",
"class":"td",
"text": "Sample Data",
click: function() {
// optional: Function to attach a click event on the object
alert("Clicked!");
}
});
// Attach the element to the document by appending it
// inside rptbody (after all existing content inside #rptbody)
$("#rptbody").append(tr);
tr.append(td);
// OR, Attach the element to the document by prepending it
// inside rptbody (before all existing content in #rptbody)
$("#rptbody").prepend(tr);
tr.append(td);
// OR, Attach the element to the document by completely replacing the content of #rptbody
$("#rptbody").html(tr);
tr.append(td);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id = "rpttable" name = "rpttable">
<thead>
Column Headers here...
</thead>
<tbody id = "rptbody" name = "rptbody">
</tbody>
</table>
I have a html table
<TABLE id="dlStdFeature" Width="300" Runat="server" CellSpacing="0" CellPadding="0">
<TR>
<TD id="stdfeaturetd" vAlign="top" width="350" runat="server"></TD>
</TR>
</TABLE>
I am dynamically adding values to it as :
function AddToTable(tblID, value)
{
var $jAdd = jQuery.noConflict();
var row= $jAdd("<tr/>").attr("className","lineHeight");
var cell = $jAdd("<td/>").attr({"align" : "center","width" : "3%"});
var cell1 = $jAdd("<td/>").html("<b>* </b>" + value);
row.append(cell);
row.append(cell1);
$jAdd(tblID).append(row);
}
Now I want a function to remove a row from this table if the value matches..as
function RemoveFromTable(tblID, VALUE)
{
If(row value = VALUE)
{
remove this row
}
}
Here VALUE is TEXT ..which needs to be matched..If exists need to remove that row,,
try this
function RemoveFromTable(tblID, VALUE){
$("#"+tblID).find("td:contains('"+VALUE+"')").closest('tr').remove();
}
hope it will work
Try like this
function RemoveFromTable(tblID, VALUE)
{
If(row value = VALUE)
{
$("TR[id="+VALUE+"]").hide(); //Assumes that VALUE is the id of tr which you want to remove it
}
}
You can also .remove() like
$("TR[id="+VALUE+"]").remove();
I highly recommend using a ViewModel in your case. So you can dynamically bind your data to a table and conditionally format it to whatever you like. Take a look at Knockout.js: http://knockoutjs.com/
function RemoveFromTable(tblID, VALUE){
$(tblID).find('td').filter(function(){
return $.trim($(this).text()) === VALUE;
}).closest('tr').remove();
}
Remove row from HTML table that doesn't contains specific text or string using jquery.
Note: If there are only two column in HTML table, we can use "last-child" attribute to find.
*$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:last-child");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: If there are more than two column in HTML table, we can use "nth-child(2)" attribute to find.
Passing column index with "nth-child(column index)"
$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:nth-child(2)");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: "DrivePilot" is nothing but text or string
I have the current table data:
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr>
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
What I want to do is groupby the TDs which are the same, and sum the values on the second td to get the total. With that in mind I´ve put the name of the product to be a class on the TR (don't know if it is needed)
and I've coded the current javascript:
$(".groupWrapper").each(function() {
var total = 0;
$(this).find(".td2").each(function() {
total += parseInt($(this).text());
});
$(this).append($("<td></td>").text('Total: ' + total));
});
by the way the current java scripr doesn't groupby.
Now i'm lost, I don't know what else I can do, or if there is a pluging that does what I want.
</tr class="Violão"> This doesn't make sense. You only close the tag: </tr>. And I'm assuming you know that since the rest of your code is proper (except for your classnames. Check this question out).
If you want to add the values of each <td> with a class of td2, see below.
Try this jQuery:
var sum = 0;
$(".td2").each(function(){
sum = sum + $(this).text();
});
This should add each number within the tds to the variable sum.
<table>
<tr class="Violão">
<td>Violão</td>
<td class="td2 8">8</td>
</tr>
<tr class="Violão">
<td>Violão</td>
<td class="td2 23">23</td>
</tr class="Violão">
<tr class="Guitarra">
<td>Guitarra</td>
<td class="td2 16">16</td>
</tr>
</table>
var dictionary = {};
$("td").each(function(){
if(!dictionary[$(this).attr("class"))
dictionary[$(this).attr("class")] = 0;
dictionary[$(this).attr("class")] += parseInt($(this).html());
});
// declare an array to hold unique class names
var dictionary = [];
// Cycle through the table rows
$("table tr").each(function() {
var thisName = $(this).attr("class");
// Add them to the array if they aren't in it.
if ($.inArray(thisName, dictionary) == -1) {
dictionary.push(thisName);
}
});
// Cycle through the array
for(var obj in dictionary) {
var className = dictionary[obj];
var total = 0;
// Cycle through all tr's with the current class, get the amount from each, add them to the total
$("table tr." + className).each(function() {
total += parseInt($(this).children(".td2").text());
});
// Append a td with the total.
$("table tr." + className).append("<td>Total: " + total + "</td>");
}
Fiddler (on the roof): http://jsfiddle.net/ABRsj/
assuming the tr only has one class given!
var sums = [];
$('.td2').each(function(){
var val = $(this).text();
var parentClass = $(this).parent().attr('class');
if(sums[parentClass] != undefined) sums[parentClass] +=parseFloat(val);
else sums[parentClass] = parseFloat(val);
});
for(var key in sums){
$('<tr><td>Total ('+key+')</td><td>'+sums[key]+'</td></tr>').appendTo($('table'));
}
I would give the table some ID and change to appendTo($('#<thID>'))
The solution:
http://jsfiddle.net/sLysV/2/
First stick and ID on the table and select that first with jQuery as matching an ID is always the most efficient.
Then all you need to do is match the class, parse the string to a number and add them up. I've created a simple example for you below
http://jsfiddle.net/Phunky/Vng7F/
But what you didn't make clear is how your expecting to get the value of the td class, if this is dynamic and can change you could make it much more versatile but hopefully this will give you a bit of understanding about where to go from here.
as i am new to jQuery i would like to ask the following, i have a table like this:
<table id="lettersGrid" border="1">
<tr>
<td>..</td>
<td>..</td>
<td>..</td>
</tr>
<tr>
<td>..</td>
<td>..</td>
<td>..</td>
</tr>
</table>
i want to use jQuery to get the value of a specific cell depending on the x and y position of it, so i have
$("td").mouseover(function(){
x=this.parentNode.rowIndex; //get the x coordinate of the cell
y=this.cellIndex; //get the y coordinate of the cell
//??whats next??
});
any help?
If all you want is the content of the cell that you are "mouseing-over"
$('td').mouseover(function(){
var content = $(this).html();
//do whatever you like with the content....
});
Edited: Use the index function to get the col/row values
$('td').mouseover(function(){
col = $(this).parent().children().index($(this));
row = $(this).parent().parent().children().index($(this).parent());
});
To Select similar rows:
$('table tr').eq(row).find('td');
To Select similar cols:
$('table tr').each(function() {
$(this).find('td').eq(col);
}
To find the value of a specific row + col
$('table tr').eq(row).find('td').eq(col).html();
i had told it at a comment before but just to be clear enough for someone with the same problem,i have found something really interesting that solved my problem, it was that simple:
$('#lettersGrid tr:eq(1) td:eq(1)').html();to get the element at col=1 row=1 starting from 0
or
$('#lettersGrid tr:nth-child(1) td:nth-child(1)').html(); to get the element at col=1 row=1 starting from 1
DEMO fiddle
$("button").click(function() {
var row = $('input.enterRow').val()- 1; // -1 CAUSE .eq() IS zero BASED
var cell = $('input.enterCell').val()- 1;
var value = $('#lettersGrid tr:eq(' + row + ') >td:eq(' + cell + ')').html();
$('.result').html( value ); // PRINT VALUE
});