Easy Java Script Code to Sort a Table by Column
By Stephen Bucaro
A Table is a powerful way to present information. You can make your table
even more powerful by giving users the ability to sort it by different columns.
In this article, I give you some simple Java Script code that you can use to
make almost any table sortable by different columns. I'll explain the code in
detail so that you can use it and modify it for your own requirements.
The first thing we need is an example table. The table below is a list of stocks
showing share price, number of shares, and put/call ratio. Don't put too much
value in the actual table contents. The numbers are fictitious, and I personally
don't even know what a put/call ratio is.
Click on a column title to sort the table based on that coulumn.
I designed the table to have a column that is text strings, a column that is
integers, a column that is floats, and a column that is fractions. This should
handle almost any kind of data you would want to place in a table.
If you want to use this example code for your own table, I recommend that you
first try it with the example table. The html code for the example table is
shown below. Cut and paste this code into the body section of your webpage.
<table id="tbl1" border=1>
Note that I gave the table an Id of tbl1. This allows us to use the documents
getElementById method to get access to the cells within the table. Note that I
did not use a table header section. I've always felt using different tags for the
cells in the first row of the table was unnecessary. The example code can be easily
modified to work with a table header, but it might be easier to just change the header
cells to regular table tags.
Note that the onclick event of each of the top table cells is used to call the
sortColunm(n) function, passing the column number to the function. Shown below
is the Java Script code block to copy and paste into the head section of your webpage.
Obviously, this is not the entire code for the sortColunm function. We'll be
adding more code to the function, explaining the purpose of each bit of code as we go.
In the code shown above, we have decremented (subtracted one) from the column number
passed to the function. The reason we do this is because, whereas humans start counting
at 1, computers start counting at 0. All this decrementation instruction does is make
the example a little more human understandable.