zm455 zm455 - 6 months ago 10
Javascript Question

Sort td values on multiple tables

I need to sort the first

td
elements of 3 tables. I must use jQuery to do it not pure javascript. Example:

<table>
<tr>
<td>cx</td>
<td>xx</td>
</tr>
</table>
<table>
<tr>
<td>bx</td>
<td>xx</td>
</tr>
</table>
<table>
<tr>
<td>ax</td>
<td>xx</td>
</tr>
</table>


The result I would like to get is:

<table>
<tr>
<td>ax</td>
<td>xx</td>
</tr>
</table>
<table>
<tr>
<td>bx</td>
<td>xx</td>
</tr>
</table>
<table>
<tr>
<td>cx</td>
<td>xx</td>
</tr>
</table>


Edit 1: that is what I'm trying to do: if you just could tell me how to get the current td element value it would be nice for me

Edit 2: Now The values in the result is the same as before sorting. Sorry for my mistake

var table = $("table");
var currentTableTd;
$.each(table, function(k, v) {
//currentTableTd = v.find("td:first-child");
//window.console.log(currentTableTd); // will log error v.find() is not a function which I understand because var v isn't a Jquery object.
//or
currentTableTd = $(this).find("td:first-child").text();
window.console.log(currentTableTd); //log undefined
})

Answer

you could use sort, then replace the html:-

var sorted = $('table').sort(function(a, b) {
  return $('td:first', a).text().localeCompare($('td:first', b).text());
}).clone();

sorted.each(function(i, e) {
  $('table').eq(i).html($(e).html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>cx</td>
    <td>xx</td>
  </tr>
</table>
<table>
  <tr>
    <td>bx</td>
    <td>xx</td>
  </tr>
</table>
<table>
  <tr>
    <td>ax</td>
    <td>xx</td>
  </tr>
</table>

Comments