tags:

views:

156

answers:

3

I want to let user click the table header to sort the table, but can just set the ascending order, can not set the descending order in the same table header. following is the function I used,

just want to know how to call the function

function sortDistrictNamedescend($a, $b) { 
    if ($a->DistrictName == $b->DistrictName) { 
        return 0; 
    } 
    return ($a->DistrictName < $b->DistrictName) ? 1 : -1; 
}

because I have already call function sortDistrictNameascend, but I also need to descending sorting the table, when user click the table header.

function sortBy(sKey)
{
   document.sortResultsForm.sSortBy.value=sKey;
   document.sortResultsForm.submit();
}

function sortDistrictNamedescend($a, $b)
{
    if ($a->DistrictName == $b->DistrictName)
    {
        return 0;
    }
    return ($a->DistrictName < $b->DistrictName) ? 1 : -1;
}

function sortDistrictNameascend($a, $b)
{
    if ($a->DistrictName == $b->DistrictName)
    {
        return 0;
    }
    return ($a->DistrictName < $b->DistrictName) ? -1 : 1;
}

if($sSortBy=="District")
{
   usort($tempArr, 'sortDistrictNameascend');
}


<table border="0" width="100%" cellspacing="2" cellpadding="2">
    <tr>
        <td class="headTable" width=15%>
            <a href="javascript:sortBy('District');"><font color=white>District</font</a>
        </td>
        <td class="headTable" width=15%>
            <a href="javascript:sortBy('Group');"><font color=white>Group</font></a>
        </td> 
        <td class="headTable" width=10%>
            <a href="javascript:sortBy('RegID');"><font color=white>RegID</font></a>
        </td> 
        <td class="headTable" width=10%>
            <a href="javascript:sortBy('Name');"><font color=white>Name</font></a>
        </td> 
    </tr>
</table>
+1  A: 

From what I can tell, you are going to need to make an AJAX call to the server and respond with html. Replace the table html with the response. Or you could reload the page on the click event, with the new order in place.

Of course, I would not do the table sorting on the server-side at all. I wold have it render with a default order, and use javascript to make changes. This means that you will have to port your sort code to javascript and toggle which function is called. You can do that toggling by setting a boolean variable or some other creative means. If you have problems sorting on the client side with javascript, feel free to ask another question.

geowa4
A: 

If you just want a sortable table, why not just a finished script, like these:

TobiX
A: 

It's usually a bad idea to transmit in HTML, especially in this case where you need to change the contents of a table. Especially since innerHTML is read only on tbody (and I think table and TR too) in IE.

I would use something like http://www.frequency-decoder.com/2006/09/16/unobtrusive-table-sort-script-revisited or what Tobix provided

Justin Johnson