S
S
shmdarya2018-03-19 14:38:30
JavaScript
shmdarya, 2018-03-19 14:38:30

How to sort data in a table as numbers and not as strings?

Good afternoon, when sorting a table in ascending / descending order, it turns out like
5aafa10631053043020095.png
this, respectively, so that the sorting is 1,2,3,4,5,6,7 ... etc. in order

function sortId(){
  var pretype = $("#pretype_sort").text();
  if(pretype == "" || pretype == "desc"){
    $("#pretype_sort").text("asc");
  }else{
    $("#pretype_sort").text("desc")
  }
  
  
    var table, rows, switching, i, x, y, shouldSwitch;
    table = document.getElementById("sorting_table");
    switching = true;
    while (switching) {
    switching = false;
    rows = table.getElementsByTagName("TR");
    for (i = 1; i < (rows.length - 2); i++) {
      shouldSwitch = false;
      x = rows[i].getElementsByTagName("TD")[0];
      y = rows[i + 1].getElementsByTagName("TD")[0];
      if(pretype == "" || pretype == "desc"){
        if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
        shouldSwitch= true;
        break;
        }
      }else{
       if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
        shouldSwitch= true;
        break;
        }
      }
      
    }
    if (shouldSwitch) {
      rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
      switching = true;
    }
    }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Stalker_RED, 2018-03-19
@Stalker_RED

parseInt()
And in general, your huge construction can be replaced with sort()
https://jsfiddle.net/zt9xLtz1/1/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question