Jump to content

How to sort searching results with JS


smus

Recommended Posts

Allow me to ask more theoretic question: for example, I've got usual PHP+MySQL search that gets some information from database. I've typed some searching values, submitted the form and got some results. Now I need to sort them onclick, for instance, alphabetically, not repeating mysql-query to the server (on client side), is it possible to make it simply using JavaScript (not AJAX)?

Link to comment
Share on other sites

If you're showing the result in a table, the quickest solution is to use an existing plugin to allow for table sorting.

https://www.google.ca/search?q=jquery+sort+table

 

If it's not a table, or you don't want to rely on a bulky library, then you can store your data in a Javascript data structure and sort the data structure, generating HTML upon sorting.

Link to comment
Share on other sites

Right, I just wanted to know if it's possible (using JS or JQuery). The task is slightly different: I'm showing the results in a table with a random number of <td>s, depending on the query; there are 3 <td>s in each <tr>. I need to reverse the order of <td>s in this table without sending additional queries. The initial order is:

<table>
<tr><td>1</td><td>2</td><td>3</td></tr> 
<tr><td>4</td><td>5</td><td>6</td></tr>
</table>

I need:

<table>
<tr><td>6</td><td>5</td><td>4</td></tr> 
<tr><td>3</td><td>2</td><td>1</td></tr>
</table>
Link to comment
Share on other sites


<!DOCTYPE html>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />

<title>Document Title</title>

<script type="text/javascript">

function sortTable(tableindex, sortType) {

var tableParent = document.getElementsByTagName('table')[tableindex];

var tableCells = tableParent.getElementsByTagName('td');

 

var cellArray = [];

for (var i = 0; i < tableCells.length; i++) {

cellArray = tableCells.innerHTML;

}

if (sortType === "d") {

cellArray.sort();

cellArray.reverse();

}

else {

cellArray.sort();

 

}

for (var i = 0; i < tableCells.length; i++) {

tableCells.innerHTML = cellArray;

}

 

 

}

 

 

 

 

</script>

<style type="text/css">

 

</style>

</head>

<body>

<table>

<tr><td>A</td><td>B</td><td>C</td></tr>

<tr><td>D</td><td>E</td><td>F</td></tr>

</table>

<button onclick="sortTable(0, 'd')">Sort Descending</button>

<button onclick="sortTable(0, 'a')">Sort Ascending</button>

<table>

<tr><td>5</td><td>4</td><td>3</td></tr>

<tr><td>2</td><td>1</td><td>6</td></tr>

</table>

<button onclick="sortTable(1, 'd')">Sort Descending</button>

<button onclick="sortTable(1, 'a')">Sort Ascending</button>

</body>

</html>

Edited by dsonesuk
  • Like 1
Link to comment
Share on other sites

Thank you very much! It works well, but there is a mistake with HTML display. It turned, the table structure is a bit more complicated: there's an additional <td> </td> between the main td's (td's that hold an information), so when, for example, number of results equal 6, the overall number of td's is 10:

<table>
<tr><td>1</td><td> </td><td>2</td><td> </td><td>3</td></tr> 
<tr><td>4</td><td> </td><td>5</td><td> </td><td>6</td></tr>
</table>

But when the row is not full, there is an additional <td> </td> at the end of it (9 td's instead of 8):

<table>
<tr><td>1</td><td> </td><td>2</td><td> </td><td>3</td></tr> 
<tr><td>4</td><td> </td><td>5</td><td> </td></tr>
</table>

So it looks not right when I reverse it. I guess, I would need somehow to exclude the last td, if the tr contains less than 3 td.

 

I can apply to main td via class(".td"), so I'm not sure if this code would work:

if ($(".td").len % 3 <> 0) 
{
  $("table.td:last").empty();
} 
Edited by smus
Link to comment
Share on other sites

OR as you loop through each cell store any cell with ' ' in separate array, its index ref will be its original position. Sort the remaining values, then loop through both, making sure when for loop index ref equals that of ' ' index print that value, then the value from sorted array afterwards.

  • Like 1
Link to comment
Share on other sites

Not as I suggested, but works

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />
        <title>Document Title</title>

        <style type="text/css">
            table {min-width: 25%; margin: 25px auto;border-spacing: 0; border-collapse: collapse; box-shadow: 3px 3px 4px rgba(0, 0, 0, 0.5);}
            td {border: 2px solid #ccc; }
            body{text-align:  center;}
        </style>
    </head>
    <body>
        <table>
            <tr><td>Apple</td><td>Cherry</td><td>Droopy</td></tr>
            <tr><td>Elephant</td><td>Fig</td><td>Banana</td></tr>
        </table>
        <button onclick="sortTable(0, 'd')">Sort Descending</button>
        <button onclick="sortTable(0, 'a')">Sort Ascending</button>
        <button onclick="sortTable(0, 'reset')">Reset</button>
        <table>
            <tr><td>5</td><td>4</td><td>3</td></tr>
            <tr><td>2</td><td>1</td><td>6</td></tr>
            <tr><td>7</td><td>10</td><td>8</td></tr>
            <tr><td>12</td><td>9</td><td>11</td></tr>
        </table>
        <button onclick="sortTable(1, 'd')">Sort Descending</button>
        <button onclick="sortTable(1, 'a')">Sort Ascending</button>
        <button onclick="sortTable(1, 'reset')">Reset</button>

        <table>
            <tr><td>1</td><td> </td><td>5</td><td>#</td><td>3</td></tr>
            <tr><td>4</td><td>#</td><td>2</td><td> </td><td>6</td></tr>
        </table>
        <button onclick="sortTable(2, 'd')">Sort Descending</button>
        <button onclick="sortTable(2, 'a')">Sort Ascending</button>
        <button onclick="sortTable(2, 'reset')">Reset</button>

        <table>
            <tr><td>Apple</td><td>Cherry</td><td>Droopy</td></tr>

            <tr><td>5</td><td>4</td><td>3</td></tr>
            <tr><td>2</td><td>1</td><td>6</td></tr>
            <tr><td>Elephant</td><td>10</td><td>8</td></tr>
            <tr><td>12</td><td>9</td><td>11</td></tr>
            <tr><td>7</td><td>Fig</td><td>1Banana</td></tr>
        </table>
        <button onclick="sortTable(3, 'd')">Sort Descending</button>
        <button onclick="sortTable(3, 'a')">Sort Ascending</button>
        <button onclick="sortTable(3, 'reset')">Reset</button>



        <script type="text/javascript">

            var tableArray = [];

            function getDefaultTableValues() {

                var tableParent = document.getElementsByTagName('table');

                for (i = 0; i < tableParent.length; i++) {
                    tableCells = tableParent[i].getElementsByTagName('td');
                    tableArray[i] = [];
                    for (var j = 0; j < tableCells.length; j++) {
                        tableArray[i][j] = tableCells[j].innerHTML;
                    }
                }
            }

            function sortTable(tableindex, sortType) {

                var tableParent = document.getElementsByTagName('table')[tableindex];
                var tableCells = tableParent.getElementsByTagName('td');
                var tableCellsToIgnore = [' ', '#'];


                var cellArray = [];
                var cellArrayString = [];
                var cellArrayNumber = [];
                var stringValidation = false;
                for (var i = 0; i < tableCells.length; i++) {

                    if (isNaN(tableCells[i].innerHTML)) {
                        //if string value set variable to true
                        stringValidation = true;
                        //copy string value to string array

                        if (tableCellsToIgnore.indexOf(tableCells[i].innerHTML) === -1) {
                            cellArrayString.push(tableCells[i].innerHTML);
                        }
                    }
                    else
                    {
                        //copy number value to number array
                        cellArrayNumber.push(parseInt(tableCells[i].innerHTML));
                    }
                }




                if (sortType === "d") {
                    if (stringValidation) {
                        // mix of numbers and string sort numbers and string arrays
                        cellArrayNumber.sort(sortNumberDesc);
                        sortTextDesc(cellArrayString);
                        //concat string and number array in order suitable for Descending
                        cellArray = cellArrayString.concat(cellArrayNumber);

                    }
                    else
                    {
                        cellArray = cellArrayNumber;
                        cellArray.sort(sortNumberDesc);
                    }
                }
                else if (sortType === "a") {

                    if (stringValidation) {
                        // mix of numbers and string sort numbers and string arrays
                        cellArrayNumber.sort(sortNumberAsc);
                        sortTextAsc(cellArrayString);
                        //concat string and number array in order suitable for Ascending
                        cellArray = cellArrayNumber.concat(cellArrayString);

                        //if all string value sort using string sorting method
                        if (cellArrayNumber.length === 0) {
                            sortTextAsc(cellArray);
                        }
                    }
                    else
                    {
                        cellArray = cellArrayNumber;
                        cellArray.sort(sortNumberAsc);
                    }

                }
                else {
                    //reset to how values were originally displayed before sorting had taken place OOOOOKKKKKKKKKKK
                    for (var i = 0; i < tableArray[tableindex].length; i++) {
                        tableCells[i].innerHTML = tableArray[tableindex][i];
                    }
                }

                if (sortType !== "reset") {
                    var m = 0;
                    for (var i = 0; i < tableArray[tableindex].length; i++) {
                        if (tableCellsToIgnore.indexOf(tableArray[tableindex][i]) === -1) {
                            tableCells[i].innerHTML = cellArray[m];
                            m++;

                        }
                        else
                        {
                            tableCells[i].innerHTML = tableArray[tableindex][i];
                        }
                    }
                }
            }
            function sortNumberAsc(a,  {
                return a - b;
            }
            function sortNumberDesc(a,  {
                return b - a;
            }

            function sortTextDesc(arr) {
                arr.sort();
                arr.reverse();
            }
            function sortTextAsc(arr) {
                arr.sort();

            }

            getDefaultTableValues();

        </script>



    </body>
</html>

Edit: add values to ignore in sort in array

 

var tableCellsToIgnore = [' ', '#'];
Edited by dsonesuk
  • Like 1
Link to comment
Share on other sites

Thanks again! Your version is good, but I've decided instead to correct some HTML display while request is processing, to simplify the task. Now there's an additional <td> </td> after each informational <td> (even at the end of a row). And my script removes the last <td> before the array reversal and after it adds new <td> at the end of the table(so that the table will have the same view if you toggle it once again).

 

There are just <td> </td> filling the rest of the space in case if there are 2 results. I think I have to somehow add fixed width to them or give <tbody> 66% of width of the table.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...