Jquery group by td with same class - javascript

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.

Related

Remove particular row of text in string based on id selected

I am trying to remove a certain table row in a string. For instance, I have the code below in a string. Lets call the variable that stores the string below temp
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
I have several buttons with id's corresponding to the number of row above. If I click the first button it has a corresponding id of 1, the second button has 2, etc.
What I am getting at is that if I hit these delete buttons, I want to remove the corresponding table row above based on what id (button) I click.
Here is my code so far.
$(".delete").click(function() {
var id = $(this).attr("id");
var temp = $("#detailsBox").val();
for (i=1; i!=id; i++) {
if (i=1) {
}
}
$(this).closest('tr').remove();
}
How would I delete a part of that string in my variable temp based off of the id(button) I click? If I choose button 1, I want to delete the first table row. Button two, second table row, etc. I know I need to replace the string, but how do I remove certain instances within the string?
Parsing HTML is dangerous. Therefore I suggest you convert your string to DOM and then manipulate on the DOM tree.
Here is a simple solution with jQuery:
var row = 1; // the row I want to remove
var temp = $("#myTextarea").value(); // get HTML
var table = $("<tbody>" + temp + "<tbody>"); // creates DOM nodes from HTML
table.find("tr").eq(row - 1).remove();
var tempWithoutRow = table[0].innerHTML;
Try yourself in JSFiddle.
You are trying to use jQuery as if that elements are in DOM... and they are not. They are just one string. So you can do something like that:
var arr = yourString.split("<tr>");
$(".delete").click(function() {
var id = $(this).attr("id");
arr = arr.splice(parceInt(id, 10)-1, 1);
}
Now you have array with the right TRs inside. All you have to do is to convert them to string again:
var htmlString;
for (var i=0; i<arr.length; i++) {
htmlString += arr[i];
}
UPDATE jQuery WAY
You can do it with jQuery too. Look at the fiddle
http://jsfiddle.net/J6HJ2/2/
You can select all the table rows and then filter down to the one you want:
$(".delete").click(function() {
var id = $(this).attr("id");
$("#my-table").find("tr").eq(id + 1).remove();//since your IDs are not zero-indexed and .eq() is
});
Docs for .eq(): http://api.jquery.com/eq
$(".delete").click(function() {
var id = $(this).attr("id");
var temp = $("#detailsBox").val();
for (i=1; i!=id; i++) {
if (i=1) {
}
}
$(this).parentNode.remove();
}
if the .delete is on the td
else if u have <td><button class="delete"></button></td>
then it's $(this).parentNode.parentNode.remove();
no need for the id if the button is inside the <tr>
Easy solution would be to give the rows meaningful ID's and use the following code:
$(".delete").click(function() {
$('#row' + $(this).id).remove();
}
If you really want to count nameless TR elements in a string you could split them into an array with split("<tr>")

getting the other values from other td in a table

Okay i have a HTML TABLE , with 4 TDs in a TR(tow) as shown in the code below:
<table>
<tr>
<td class="1">Lemon</td>
<td class="2">Orange</td>
<td class="3">Tea</td>
<td class="4">Get</td>
</tr>
<tr>
<td class="1">Apple</td>
<td class="2">Tomato</td>
<td class="3">Pineapple</td>
<td class="4">Get</td>
</tr>
</table>
How can i use jQuery to make , when a#GET is clicked , it will go get the class 1 , 2 , 3 values which is in the same table row as it.
For example , i click on the a#get in the first row , i will get Lemon , orange , tea as the results.
I use the jQuery code below but it's not working:
$(document).ready(function(){
$('a#get').click(function(e){
e.preventDefault();
var val1 = $(this).parent().find('td.1').html();
var val2 = $(this).parent().find('td.2').html();
var val3 = $(this).parent().find('td.3').html();
alert(val1 + val2 + val3);
});
});
Any ideas on how can i do this or what i'm doing wrong?
thanks!
See Working Demo
You should use unique id, here is modfifed code:
$(document).ready(function(){
$('a.get').click(function(e){
e.preventDefault();
var val1 = $(this).closest('tr').find('td.1').html();
var val2 = $(this).closest('tr').find('td.2').html();
var val3 = $(this).closest('tr').find('td.3').html();
alert(val1 + val2 + val3);
});
});
Using parent you were getting back to td because link is inside that, you needed to get back to tr which is done through closest('tr'). Also html has been modified for link element to have unique id.
Get
You're calling .find() inside the td element, while you actually need to call it in tr, which is one level higher.
Replace $(this).parent().find(...) with $(this).parent().parent().find(...).
(And you should make your IDs unique, as pimvdb suggested.)
There's no point adding a class to the cells, if they're just numerical - you can use eq() for that.
Here's how I'd do it:
$('#table-id tr').each(function() {
var tds = $(this).find('td');
$(this).find('a.get').click(function() {
alert(tds.eq(0).html() + tds.eq(1).html() + tds.eq(2).html());
return false;
});
});

Joining cells with Javascript

I'm trying to do my best effort planning how to do this but I can't...
Example:
I have a table with id, but not td id's...
I have four td's en each tr.
<tr>
<td>one</td><td>two</td><td>three</td><td>four</td></tr>
<tr>
<td>aaa</td><td>bbb</td><td>ccc</td><td>ddd</td></tr>
So, what I want is to generate in the same table this output:
<tr>
<td>one two</td><td>three four</td></tr>
<tr>
<td>aaa bbb</td><td>ccc ddd</td></tr>
From 4 td to 2 td in the table showing the four values.
Edit: I misread your target HTML and gave you something you weren't looking for. Here's the corrected code that gives you the HTML result you want:
http://jsfiddle.net/gilly3/DxVAS/6/
var t = document.getElementById("myTable");
for (var i = t.rows.length - 1; i >= 0; i--) {
var r = t.rows[i];
r.cells[0].innerHTML += " " + r.removeChild(r.cells[1]).innerHTML;
r.cells[1].innerHTML += " " + r.removeChild(r.cells[2]).innerHTML;
}
Have fun: http://jsfiddle.net/ungarida/4C29u/

Get the value of a tables's cell depending on the x and y coordinates

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
});

How to get a table column index in JavaScript knowing its class?

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.

Categories

Resources