File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes HTML, CSS and JavaScript and the fly likes Sorting in JavaScript Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Reply Bookmark "Sorting in JavaScript" Watch "Sorting in JavaScript" New topic
Author

Sorting in JavaScript

deepak kukreja
Ranch Hand

Joined: Aug 13, 2001
Posts: 54
Hi,

I have a table, which is to be made sortable. When the user clicks on first column header it should sort on the first column i.e. Order by first column
, and then under the first column data, order the data in second column......and so on. User can click on any of the columns so the order by will also change accordingly.

as an example.

if the columns available are:

Project name, Employee name.

If there are two projects which starts from letter 'k', then after sorting on projects column, it should sort on employee name column for those two projects.

Is it possible to do this with javascript.
Could somebody provide me with good links?


Deepak<br />SCJP
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15357
    
    6
This is the mess I always wanted to get into with my table, but I never got around to it since I am working on my book.

I have not seen it anywhere online.
Amol Sonawane
Greenhorn

Joined: May 23, 2004
Posts: 3
Hi Deepak
This can be done using javascript. You can follow this approach

1)Use a constructor to store all the column values. For example

function person(firstName, lastName, age)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Age = parseInt(parseFloat(age));
}
2)Store all the objects in an array
e.g. people[people.length++] = new person("amol", "sonawane", 22);
Here values will come from your table columns

3)Write the appropriate sorting function
e.g. function sortByFirstName(a, b)
{
var x = a.FirstName.toLowerCase();
var y = b.FirstName.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
4)Use the inbuilt sort function of javascript arrays
e.g people.sort(sortByFirstName);
5) Populate your html table dynamically using this sorted array

Hope this answers your problem
regards
- amol
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Sorting in JavaScript
 
Similar Threads
How to Sort a Data Table using Headers & Other question
Sorting data in tabel; what pattern?
pagination in jsp
Struts validation
Table sorting queries