Dom + Javascript Sorts table data in native browsers

Source: Internet
Author: User
Tags end functions object model string sort sorts string format first row
dom|javascript| Browser | sort | data

Sort table data in a native browser
In Web applications, data is returned to the client from the server side and displayed in tabular form. If you want to sort the dataset by the column you specify, the general practice is to make a request to the server, and the server-side program to retrieve the data sorted by the specified column from the database, back to the client, and the page to display the sorted data again.

The following disadvantages are used in this way:
1-response time delay, each sort will send a request to the server side, waiting for the result to return, while increasing network load.
2-programming complexity, poor maintainability, and client and server-side code coupling is very high, both the client and server side handle the column names involved in sorting, sorting, and if there are paging and query conditions, they need to be retained in the client page, the sort request is transferred back to the server side, when the number of parameters is very easy to error.
3-The degree of reuse is very low, for different tables, it is difficult to abstract a common program to share, need to write code to achieve, increase the workload.

Now in another perspective, since the data has been downloaded to the client, it is not necessary to reorder the server-side, as long as the data in the browser to reorder the display. To achieve this goal, the following points are required:
1-Get the data to be sorted in the table and put it in a 2-D array.
2-Sort the 2-D array.
3-Update the table with the sorted data.

These goals can be achieved by using the browser-supported Dom (Document Object Model) and JavaScript.

There are usually a lot of <table&gt in the page, and to get the table where you want to sort the data, you need to add an id attribute in <table> to make it easier for the document object to use getElementById to get the Table object. For example, the table to be sorted is defined as follows:
<table id= "St" >
<tr>
<td>1</td>
<td>2</td>
</tr>
</table>

In JavaScript, you can get a Table object with the var objtable = document.getElementById ("St"), which is defined as an element in the DOM.

Then use var objrows = Objtable.getelementsbytagname ("tr") to get all the row objects in the table, Objrows.length return the row number of the table; var rowi = Objrows[i]. getElementsByTagName ("TD") gets all <td> nodes in line I, I count from 0, Rowi.item (j) can get the first line, the J column node, the node innerHTML is the node <td> The content between </td>.

Get the form data to the 2-D array code see source code, here's a bit.

The following describes the construction and ordering of 2-D arrays in JavaScript.
JavaScript does not support 2-d arrays. Therefore, an array of arrays is needed to simulate a 2-D array by first defining a 1-d array, the number of elements being 2-dimensional, and then assigning a value to each element with an array of elements with a 2-dimensional array of columns. The construction code is as follows:

var rows = new Array (R); R is the number of rows
for (var i = 0; i < rows.length; i++) {
Rows[i] = new Array (C); C is the number of columns
}


Use the Array.Sort (comparer) in JavaScript to sort the elements in rows, which are compared by a redefined comparison function. To sort by the size of the elements in the J column, simply define the following function:

function Comparecol (a,b) {

if (A[j] < b[j])
return-1;

if (A[j] > B[j])
return 1;

return 0;

}

Because Comparecol can only have two parameters, J is defined as a global variable.

Rows.sort (Comparecol) enables you to sort rows according to the size of the J-column value. According to JavaScript documents, the string comparison size is based on the size of its Unicode encoding, there is no problem with the English ordering, the Chinese sort is not the usual phonetic ordering, which requires JavaScript to provide localized support, no JavaScript This feature is currently found. This feature is available in Java in Java.text.Collator implementations.


The above describes the main idea of sorting the data in the browser locally, for ease of use, encapsulate these functions, provided by JavaScript functions, stored in sorttable.js files, and <script type=text/in the pages needed JavaScript src= ' sorttable.js ' ></script> introduced.


The sort function prototypes and usage methods are described below.

Functions 1 function sorttable (tableid,sortcol,comparetype)
Sorts the data in a specified table in a page, usually the first behavior header row, sorted from the second row, the first call in ascending order, the second in descending order, and then rotated.
TableId is the value of ID in <table id= ' >, unique on the same page.
Sortcol the column in which the data used to compare the size is sorted, counting starting from 1.
Comparetype the way to compare size when sorting, S-by-string comparison size, n-by-number comparison size.



Functions 2 function Sorttableinrange (tableid,sortcol,comparetype,startrow,endrow,startcol,endcol)

Sort the area data specified in the table, sometimes the data is first listed as the serial number, and the last behavior is aggregated, which does not need to be sorted, and can be used to sort some of the data.

TableId is the value of ID in <table id= ' >, unique on the same page.
Sortcol the column in which the data used to compare the size is sorted, counting starting from 1.
Comparetype the way to compare size when sorting, S-by-string comparison size, n-by-number comparison size.
Startrow,endrow to sort the range start and end line numbers, counting starting from 1. For example, sort lines 2nd through 7th, startrow=2,endrow=7
Startcol,endcol to sort the range start and end column numbers, counting starting from 1.





The problems that exist:
The Chinese can not be sorted by pinyin.


Issues to be aware of:
The table to be sorted must be marked with an ID and passed as a parameter to the sort function, and the data in the table should be sortable, otherwise the result is unpredictable; the table to be sorted cannot have nested tables or the sort error.


This function has been run through in IE6.0, FireFox1.01. The source code and example code are shown later.




Resources:

Danny Goodman with Michael Morrison JavaScript Bible 5th, John Wiley and Sons 2004

David Flanagan JavaScript The definitive Guide 4th, O ' Reilly 2001





Source code: To run the example, the JavaScript code needs to be saved to the Sorttable.js file, and the HTML part of the code is saved to another file in the same directory.


Sorttable.js

//=========================================================
//
JavaScript functions that sort data rows in a browser page table on the local computer
//
Author William qq:22967225
Create Date 2005-12-2
Version 1.0
//=========================================================

Column index for sort
var Indexcol;
Comparison functions, used when array.sort () sorting.
This function compares the size of the array element Array1[indexcol] and the element Array2[indexcol]unicode value
function Arraycompare (array1,array2) {
Alert (array1.length+ "-" +array1[indexcol]);
if (Array1[indexcol] < Array2[indexcol])
return-1;
if (Array1[indexcol] > Array2[indexcol])
return 1;

return 0;

}
Compare the numeric size of the array element Array1[indexcol] and element Array2[indexcol]
function Arraycomparenumber (array1,array2) {

if (parseint (Array1[indexcol]) < parseint (Array2[indexcol))
return-1;
if (parseint (Array1[indexcol]) > parseint (array2[indexcol))
return 1;

return 0;
}

Compare size with arraycompare in reverse use
function Arraycomparerev (array1,array2) {

if (Array1[indexcol] < Array2[indexcol])
return 1;
if (Array1[indexcol] > Array2[indexcol])
return-1;

return 0;

}
Compare size with arraycomparenumber in reverse use
function Arraycomparenumberrev (array1,array2) {
if (parseint (Array1[indexcol]) < parseint (Array2[indexcol))
return 1;
if (parseint (Array1[indexcol]) > parseint (array2[indexcol))
return-1;

return 0;
}

Define a 2-dimension array
function Biarray (rows,cols) {

Simulate multidimension Array
This.rows = rows;
This.cols = cols;

Construct array
var lines = new Array (rows);
for (var i = 0;i < Lines.length; i++) {
Lines[i] = new Array (cols);
}


Sets the element value of the array in (I,J) to
This.setelement = function (i,j,value) {lines[i][j] = value;};

Gets the value of an array at the (I,J) element
This.getelement = function (i,j) {return lines[i][j];

Returns the array where line I is located
This.getline = function (i) {return lines[i];};

The rows of the array are sorted according to the value of the J-column string, and the sorted result is ascending
This.sortline = function (j) {
Indexcol = j;
Lines.sort (Arraycompare);
};

The rows of the array are sorted according to the value of the J column, and the sorted result is ascending
This.sortlinebynumber = function (j) {
Indexcol = j;
Lines.sort (Arraycomparenumber);
};

The rows of the array are sorted according to the value of the J-column string, and the sorted result is reversed
This.sortlinerev = function (j) {
Indexcol = j;
Lines.sort (Arraycomparerev);
};

The row of the array is sorted according to the value of the J column, and the sorted result is in reverse order
This.sortlinebynumberrev = function (j) {
Indexcol = j;
Lines.sort (Arraycomparenumberrev);
};
To convert a two-dimensional array into a string format
this.tostring = function () {
var rst = "";
for (var i = 0; i < lines.length; i++) {
for (var j = 0; J < Lines[i].length; J + +) {
RST + + lines[i][j];
rst = ' t ';
}
rst = = ' \ n ';
}
return rst;
};
}//End of Biarray define

Ascending or Descending
var asce = true;

/**
Sort data in a specified range in a table
TableId the ID of the table to be sorted, the value format is <table id= "TB1" >
Sortcol the column number used for sorting, counting starting from 1
Comparetype when sorting, S-by-string comparison, n-by-numeric comparison
StartRow the start line number of the sort range, counting from 1
Endrow Sort range Ending line number, counting starting from 1
Startcol sort range Starting column number, counting starting from 1
Endcol Sort range End column number, counting starting from 1
*/
function Sorttableinrange (tableid,sortcol,comparetype,startrow,endrow,startcol,endcol) {


try{
var table = document.getElementById (tableId);
Get all Row object of the table
var objrows = Table.getelementsbytagname ("tr");
alert (objrows.length);

Endrow = (Endrow < objrows.length? endRow:objRows.length);

var sortrows = Endrow-startrow + 1;
Alert ("Sortrows" +sortrows);
if (Sortrows < 2)//only one Line,don ' t sort
return;


Endcol = (Endcol < Objrows[1].getelementsbytagname ("TD"). Length? Endcol:
Objrows[1].getelementsbytagname ("TD"). length);


Column number of sort
var cols = objrows[1].childnodes.length;
var cols = endcol-startcol + 1;



Define a array to store table cell and sort them
var tabdata = new Biarray (sortrows,cols);


var ari = 0;
retrived table cell data save to array
for (i = startRow-1 i < Endrow; i++) {
Retrived All <td> cell
var cells = Objrows[i].getelementsbytagname ("TD");

var arj = 0;
for (var j = StartCol-1 J < Endcol; J + +) {
Tabdata.setelement (Ari,arj,cells.item (j). InnerHTML);
arj++;

}
ari++;
}

if (ASCE) {
if (Comparetype = = "N" | | comparetype = = ' n ')
Tabdata.sortlinebynumber (Sortcol-startcol);
Else
Tabdata.sortline (Sortcol-startcol);
ASCE = false;
}else{
if (Comparetype = = "N" | | comparetype = = ' n ')
Tabdata.sortlinebynumberrev (Sortcol-startcol);
Else
Tabdata.sortlinerev (Sortcol-startcol);
ASCE = true;
}
Ari = 0;
Update table data with array
for (i = startRow-1 i < Endrow; i++) {
Retrived All <td> cell
var cells = Objrows[i].getelementsbytagname ("TD");

ARJ = 0;
for (var j = StartCol-1 J < Endcol; J + +) {
Cells.item (j). InnerHTML = Tabdata.getelement (ARI,ARJ);
arj++;
}
ari++;
}

}catch (e) {
Alert (e);
}
}

/**
Sort the data rows except the first row of the table, which is Sortyableinrange (Tableid,sortcol,comparetype,2,tabrows,1,tabcols)
The special case.
TableId the ID of the table to be sorted, the value format is <table id= "TB1" >
The column number used for sorting, counting starting from 1
Comparetype when sorting, S-by-string comparison, n-by-numeric comparison
*/
function SortTable (tableid,sortcol,comparetype) {


try{
var table = document.getElementById (tableId);
Get all Row object of the table
var objrows = Table.getelementsbytagname ("tr");
alert (objrows.length);


var endrows = objrows.length;

if (Endrows < 2)//only one Line,don ' t sort
return;

Column number of table
var cols = objrows[1].getelementsbytagname ("TD"). Length;


Sorttableinrange (Tableid,sortcol,comparetype,2,endrows,1,cols);

}catch (e) {
Alert (e);
}
}

==========javascript Code End ============

Example HTML page code

<script type= "Text/javascript" src= "Sorttable.js" >
</script>
<body>
General Sort Example <br>
<table id= "T1" border= "1" >
<tr>
&LT;TD width= "20%" ><a href= "#" > City </a></td>
&LT;TD width= "30%" ><a href= "#" > Brand </a></td>
&LT;TD width= "30%" ><a href= "#" > Sales </a></td>
</tr>
<tr>

<td><a href= "#" > Beijing </a></td>
<td>GOOGLE</td>
<td>64</td>
</tr>
<tr>
<td> Shanghai </td>
<td>CISCO</td>
<td>54</td>
</tr>
<tr>
<td> Guangzhou </td>
<td>MS</td>
<td>9</td>
</tr>
<tr>

<td> Nanjing </td>
<td>INTEL</td>
<td>120</td>
</tr>
</table>

<br> sort examples of partial data (sort 2–5 rows, 第2-4 column areas) <br>
<table id= "T2" border= "1" >
<tr>
<td> Serial Number </td>
&LT;TD width= "20%" ><a href= "#" > City </a></td>
&LT;TD width= "30%" ><a href= "#" > Brand </a></td>
&LT;TD width= "30%" ><a href= "#" > Sales </a></td>
</tr>
<tr>
<td>1</td>
<td><a href= "#" > Beijing </a></td>
<td>GOOGLE</td>
<td>64</td>
</tr>
<tr>
<td>2</td>
<td> Shanghai </td>
<td>CISCO</td>
<td>54</td>
</tr>
<tr>
<td>3</td>
<td> Guangzhou </td>
<td>MS</td>
<td>9</td>
</tr>
<tr>
<td>4</td>
<td> Nanjing </td>
<td>INTEL</td>
<td>120</td>
</tr>
</table>
</body>



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.