sort table, una ayuda pofavo
Hace algun tiempo meddle, puso esta direccion donde dan un magnifico script para ordenar tablas,dinamicamente sin tener que recargar la pagina, ooohhhhhhhhhhhhhhhhh!!!!!!
pero ahora tengo un pequeño p'oblema, este script te coge las cabeceras y te las convierte en enlaces que disparan la funcion para ordenar las tablas, el caso es que yo quiero meter la tabla dentro de un <div style:overflow=auto> para poder scrollearla y dejar las cabeceras fuera.
Hay alguna manera de dispara estas funciones desde fuera de la propia tabla??????
Lo pregunto por si alguien ha tenido que lidiar antes con este script, hace tiempo solucione el problema con un script distinto que era este:
<code>
var lastTableNumber;
var lastColumnNumber;
var lastOrder;
function sortTableRows ()
{
// get all tables in this document
tables = document.getElementsByTagName ('table');
// iterate through all the tables, to make the tables sortable
for (var tableNumber = 0; tableNumber < tables.length; tableNumber++)
{
// check if the table uses the thead-element
if (thead = tables[tableNumber].getElementsByTagName ('thead')) headerRow = thead[0].getElementsByTagName ('tr')[0];
// if not, use the first row of this table as header
else headerRow = tables[tableNumber].getElementsByTagName ('tr')[0];
// iterate through all the th-elements, to add the onclick event with the 'sortColumn'-function attached
tableHeaders = headerRow.getElementsByTagName ('th');
for (var columnNumber = 0; columnNumber < tableHeaders.length; columnNumber++)
{
// attach the 'sortColumn'-function
if (!document.all && document.getElementById)
{
// this method works fine in Mozillla, but IE doesn't do anything, really.
// It's a pity, 'cause when using the setAttribute-function you can style
// the element with CSS using:
// th[onclick] { /* some properties here */ }
tableHeaders[columnNumber].setAttribute ('onclick', 'sortColumn(' + tableNumber + ', ' + columnNumber + ');');
}
else if (document.all && document.getElementById)
{
tableHeaders[columnNumber]['onclick'] = new Function ('sortColumn(' + tableNumber + ', ' + columnNumber + ')');
//tableHeaders[columnNumber].style.cursor = 'hand';
}
}
}
}
function sortColumn (tableNumber, columnNumber)
{
// set some variables we're going to use
var rowData = new Array ();
var rowDataSorted = new Array ();
var rowToBeRemoved = new Array ();
var rowToBeInserted = new Array ();
var table, tbody, rows, firstRow, order;
// check wheter it should be ordered ascending or descending
if (lastTableNumber == tableNumber && lastColumnNumber == columnNumber)
{
if (lastOrder == 'ascending') order = 'descending';
else if (lastOrder == 'descending') order = 'ascending';
}
else order = 'ascending';
// in case there is a tbody-element, we'll use the rows nested in this element ...
table = document.getElementsByTagName ('table')[tableNumber];
if (table.getElementsByTagName ('tbody'))
{
tbody = table.getElementsByTagName ('tbody')[0];
firstRow = 0;
}
// ... otherwise we'll use the rows that are directly nested in the table-element, starting with the second (assuming the first row is the header)
else
{
tbody = table;
firstRow = 1;
}
// put all the rows in an array, so we can access each easily
rows = tbody.getElementsByTagName ('tr');
// iterate through the rows, and put the data according to which the table must be sorted in an array
for (var rowNumber = firstRow; rowNumber < rows.length; rowNumber++)
{
data = rows[rowNumber].getElementsByTagName ('td')[columnNumber].firstChild.nodeValue;
rowData[rowData.length] = new Array (rowNumber, data);
}
// choose the relevant sorting method, according to the first row:
// - the data is numeric
if (rowData[0][1].match(/^[\d\.]+$/)) rowDataSorted = rowData.sort (numeric);
// - no particular type of data recognized, use the standard sorting-method
else rowDataSorted = rowData.sort (normal);
// iterate through the rows, that now are in the correct order ...
for (var x = 0; x < rowDataSorted.length; x++)
{
originalRow = rows[(rowDataSorted[x][0])];
// ... create a clone of the orignal row, and register it to be inserted in its new place ...
rowToBeInserted[rowToBeInserted.length] = originalRow.cloneNode (true);
// ... and register the original row to be removed, because its place isn't correct anymore
rowToBeRemoved[rowToBeRemoved.length] = originalRow;
}
// reverse order if we sort this column descending
if (order == 'descending') rowToBeInserted.reverse ();
// insert the clones into the table's body
for (var x = 0; x < rowToBeInserted.length; x++)
{
// the following two lines are for the alternate row color
if (x%2) rowToBeInserted[x].setAttribute ('class', 'even');
else rowToBeInserted[x].setAttribute ('class', 'odd');
tbody.appendChild (rowToBeInserted[x]);
}
// remove the original, now superfluous, rows
for (var x = 0; x < rowToBeRemoved.length; x++)
{
tbody.removeChild (rowToBeRemoved[x]);
}
// register a class to the header of the column according to which the table has been sorted, so one can style a ascending and descending sorted column differently
// check if the table uses the thead-element
if (thead = tables[tableNumber].getElementsByTagName ('thead')) headerRow = thead[0].getElementsByTagName ('tr')[0];
// if not, use the first row of this table as header
else headerRow = tables[tableNumber].getElementsByTagName ('tr')[0];
// iterate through all the th-elements, to add the onclick event with the 'sortColumn'-function attached
tableHeaders = headerRow.getElementsByTagName ('th');
for (var columnNumberTwo = 0; columnNumberTwo < tableHeaders.length; columnNumberTwo++)
{
if (columnNumberTwo == columnNumber) tableHeaders[columnNumberTwo].setAttribute ('class', order);
else tableHeaders[columnNumberTwo].setAttribute ('class', '');
}
// remember according to which column from which table we've sorted, and in what order, so when one sorts this column again, we sort it in reverse order
lastTableNumber = tableNumber;
lastColumnNumber = columnNumber;
lastOrder = order;
}
function numeric (foo, bar)
{
valueOne = foo[1];
valueTwo = bar[1];
return valueOne - valueTwo;
}
function normal (foo, bar)
{
x = new Array (foo[1], bar[1]);
x.sort ();
if (x[0] == foo[1]) return -1;
else if (x[0] == x[1]) return 0;
else return 1;
}
</code>
pero meddle me dijo que era sucio (e insincero ;-)) y ademas ahora sin venir a cuento me da un error que dice que thead.0 is null or not a object.
en fin una ayudita para salir del atolladero, por cierto el html que llama a este segundo script es este:
<code>
<html>
<head>
<title>sort table rows</title>
<style type="text/css">
@import 'stylesheet.css';
</style>
<script type="text/javascript" src="sortTableRows.js"></script>
</head>
<body onload="sortTableRows ();">
<table width="350" border="0" cellspacing="0" cellpadding="0" class="cabecera">
<tr>
<td width="30" onClick="sortColumn(1,1);">ID</td>
<td width="169" onClick="sortColumn(1,2);">Song Name</td>
<td width="95" onClick="sortColumn(1,3);">Artist</td>
<td width="56" onClick="sortColumn(1,4);">Time</td>
</tr>
</table>
<DIV style="height:150px;WIDTH=380PX;overflow:auto;">
<table width="350" cellspacing="0" id="fab" >
<THEAD>
<TR>
<TD></TD>
<TD></TD>
<TD></TD>
<TD></TD>
</TR>
</THEAD>
<tbody>
<!-- <tbody style="height:100px;overflow:auto;overflow-y="100""> -->
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo" width="25">2</td><td class="cuerpo" width="168">Another Chance (original mix)</td><td class="cuerpo" width="94">Roger Sanchez</td><td class="cuerpo" width="53">7.30</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">4</td><td class="cuerpo">At Least We Tried</td><td class="cuerpo">Moby</td><td class="cuerpo">4.08</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">3</td><td class="cuerpo">8 Ball</td><td class="cuerpo">Underworld</td><td class="cuerpo">8.51</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">1</td><td class="cuerpo">Happiness Is A Warm Gun</td><td class="cuerpo">Tori Amos</td><td class="cuerpo">9.55</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">2</td><td class="cuerpo">Another Chance (original mix)</td><td class="cuerpo">Roger Sanchez</td><td class="cuerpo">7.30</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">4</td><td class="cuerpo">At Least We Tried</td><td class="cuerpo">Moby</td><td class="cuerpo">4.08</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">3</td><td class="cuerpo">8 Ball</td><td class="cuerpo">Underworld</td><td class="cuerpo">8.51</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">1</td><td class="cuerpo">Happiness Is A Warm Gun</td><td class="cuerpo">Tori Amos</td><td class="cuerpo">9.55</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">2</td><td class="cuerpo">Another Chance (original mix)</td><td class="cuerpo">Roger Sanchez</td><td class="cuerpo">7.30</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">4</td><td class="cuerpo">At Least We Tried</td><td class="cuerpo">Moby</td><td class="cuerpo">4.08</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">3</td><td class="cuerpo">8 Ball</td><td class="cuerpo">Underworld</td><td class="cuerpo">8.51</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">1</td><td class="cuerpo">Happiness Is A Warm Gun</td><td class="cuerpo">Tori Amos</td><td class="cuerpo">9.55</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">2</td><td class="cuerpo">Another Chance (original mix)</td><td class="cuerpo">Roger Sanchez</td><td class="cuerpo">7.30</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">4</td><td class="cuerpo">At Least We Tried</td><td class="cuerpo">Moby</td><td class="cuerpo">4.08</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">3</td><td class="cuerpo">8 Ball</td><td class="cuerpo">Underworld</td><td class="cuerpo">8.51</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">1</td><td class="cuerpo">Happiness Is A Warm Gun</td><td class="cuerpo">Tori Amos</td><td class="cuerpo">9.55</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">2</td><td class="cuerpo">Another Chance (original mix)</td><td class="cuerpo">Roger Sanchez</td><td class="cuerpo">7.30</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">4</td><td class="cuerpo">At Least We Tried</td><td class="cuerpo">Moby</td><td class="cuerpo">4.08</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">3</td><td class="cuerpo">8 Ball</td><td class="cuerpo">Underworld</td><td class="cuerpo">8.51</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">1</td><td class="cuerpo">Happiness Is A Warm Gun</td><td class="cuerpo">Tori Amos</td><td class="cuerpo">9.55</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">2</td><td class="cuerpo">Another Chance (original mix)</td><td class="cuerpo">Roger Sanchez</td><td class="cuerpo">7.30</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">4</td><td class="cuerpo">At Least We Tried</td><td class="cuerpo">Moby</td><td class="cuerpo">4.08</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">3</td><td class="cuerpo">8 Ball</td><td class="cuerpo">Underworld</td><td class="cuerpo">8.51</td></tr>
<tr OnMouseOver="bgColor='#EBEBE4'" OnMouseOut="bgColor=''" ><td class="cuerpo">1</td><td class="cuerpo">Happiness Is A Warm Gun</td><td class="cuerpo">Tori Amos</td><td class="cuerpo">9.55</td></tr>
</tbody>
</table>
</DIV>
</body>
</html>
</code>
meddle
ah si, estoy empezando a temer que soy propenso a la promiscuidad. me llevais por mal camino... como os pille mi mujer... ;)
hartum
no,no, ese fue orange y le hiciste sexo duro y guarro por detras, yo soy una srta, tratame con cariño juas juas juas
meddle
HARTUM
Te he dicho alguna vez que te quiero? bueno pues que sepas que tienes un par de birras pagadas intercambiables por cubata o similar ;-)
p.d: no lo quites hasta el viernes anda
jaja, si, creo que ya te habias declarado antes ;)
no suelo quitar mis ejemplos, en principio estaran ahi mientras tenga subdominio
hartum
Te he dicho alguna vez que te quiero? bueno pues que sepas que tienes un par de birras pagadas intercambiables por cubata o similar ;-)
p.d: no lo quites hasta el viernes anda
meddle
bueno, pa chulo mi pirulo, ya esta...ba porque luego me he dado cuenta que tienes un problema de concepto: al estar separando el header de la tabla de datos del nuevo header que esta fuera del scroll, lo que pasa es que los anchos de las columnas no te van a coincidir, a no ser que siempre les asignes un tamaño fijo igual para todos.
te dejo lo que tengo y lo del ancho lo haces tu, ala.
http://meddle.dzygn.com/tests/sorttable/
otra cosa, imprescindible que el TR primero vaya justo seguido de la tabla y esta vaya JUSTO seguido del DIV:
<code><div class="container"><table id="t1" class="sortable"><tr><th>Name</th><th>Salary</th><th>Extension</th><th>Start date</th></tr></code>(todo en una linea, por cuestiones de ahorro de condicionales y bucles)
otro dia ya arreglaremos el script, que aunque me gusta, es un poquito sucio todo sin namespace.
hartum
tu solo te contestas eh? jejejejejeje
mi problema no es el div, mejor te digo exactamente lo que quiero, quiero una tabla que cumpla las siguientes condiciones:
-que a partir de cierta altura aparezca un scroll
-que las cabeceras de la tabla esten fuera del scroll
-que pinchando en las cabeceras se ordenen por dicha cabecera
y ahora el intringulis esta en reunir todos estos elementos, por un lado tengo un script paar ordenar la tabla pinchando en la cabecera, por otro tengo mi scroll, que lo puedo aplicar tanto en un div como en la tabla, como hago para combinarlos como yo quiero?
meddle
a ver, lo que tu quieres hacer, tal como está montado el js es complicado de cambiar, porque hay que tocar eventos y todo el rollo.
meddle
como eso no funciona, tienes que cambiar la funcion ts_makeSortable de manera que esconda (display = "none") la primera fila (asume que es el header) y ademas añada una capa (antes de la tabla y del div que la incluye y por tanto fuera del alcance del overflow)
si necesitas mas ayuda me avisas
meddle
pregunta chorra: si el problema es el div que contiene la tabla (poara poder hacer scroll): ¿por que no usas el style:overflow=auto directamente en la tabla?