0

I'm trying to sort tr but I've no luck by far.

Here is my tr structure.

<tr>
    <td>
        <a href="./BlueSky-TexasHealthResources/index.php" >Blue Sky-Texas</a>
    </td>
    <td>
        <a href="./BlueSky-TexasHealthResources/view.php">View Data</a>
    </td>
    <td id="blue_sky_texas">

    </td>
</tr>
<tr>
    <td id = 'bj'>
        <a href="./BountyJobs/index.php" >Bounty Jobs</a>
    </td>
    <td>
        <a href="./BountyJobs/view.php">View Data</a>
    </td>
</tr>

Here is Javascript that I've tried by far.

<script type="text/javascript">
var $tr = $("tr");

$(document).ready(function () {
    var alphabeticallyOrderedTr = $tr.sort(function (a, b) {
        return $(a).find("a:first").text().toLowerCase().localeCompare($(b).find("a:first").text().toLowerCase());           
    });
    $("#container").html(alphabeticallyOrderedTr);
});
</script>

And below is the image for table (unsorted using above code :( ). enter image description here

Mubin
  • 4,325
  • 5
  • 33
  • 55
  • Possible duplicate of [jQuery table sort](http://stackoverflow.com/questions/3160277/jquery-table-sort) – IlGala Oct 28 '15 at 15:36

1 Answers1

1

.sort() is Array.prototyope method, not jQuery method. Try adding .get() or .toArray() before .sort(function(){}) called ; e.g., $tr.get().sort(

$(document).ready(function() {
  var $tr = $("tr");
  var alphabeticallyOrderedTr = $tr.get().sort(function(a, b) {
    return $(a).find("a:first").text().toLowerCase().localeCompare($(b).find("a:first").text().toLowerCase());
  });
  $("#container").append(alphabeticallyOrderedTr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table id="container">
  <tr>
    <td>
      <a>Y Jobs</a>
    </td>
  </tr>
  <tr>
    <td>
      <a>Z Jobs</a>
    </td>
  </tr>
  <tr>
    <td id='bj'>
      <a href="./BountyJobs/index.php">Bounty Jobs</a>
    </td>
    <td>
      <a href="./BountyJobs/view.php">View Data</a>
    </td>
  </tr>
  <tr>
    <td>
      <a>X Jobs</a>
    </td>
  </tr>
  <tr>
    <td>
      <a href="./BlueSky-TexasHealthResources/index.php">Blue Sky-Texas</a>
    </td>
    <td>
      <a href="./BlueSky-TexasHealthResources/view.php">View Data</a>
    </td>
    <td id="blue_sky_texas">

    </td>
  </tr>
</table>
guest271314
  • 1
  • 15
  • 104
  • 177