lundi 3 avril 2017

How to sort table by checkbox checked attribute

I'm new to javascript, and I've got a problem I can't solve for some time... I need to sort table on the fly. The (borrowed) code is:

function sortTable(n) {
      var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
      table = document.getElementById("myTable2");
      switching = true;
      dir = "asc"; 

      while (switching) {

        switching = false;
        rows = table.getElementsByTagName("TR");
        for (i = 1; i < (rows.length - 1); i++) {
          shouldSwitch = false;
          x = rows[i].getElementsByTagName("TD")[n];
          y = rows[i + 1].getElementsByTagName("TD")[n];

          if (dir == "asc") {
            if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
              shouldSwitch= true;
              break;
            }
          } else if (dir == "desc") {
            if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
              shouldSwitch= true;
              break;
            }
          }
        }
        if (shouldSwitch) {
          rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
          switching = true;
          switchcount ++; 
        } else {
          if (switchcount == 0 && dir == "asc") {
            dir = "desc";
            switching = true;
          }
        }
      }
    }

It works fine with text/numeral values, but the problem is that one of the columns in the table consists of checkboxes. And idea is to sort the table the way rows with checked checkboxes are on top (/bottom, depending on ascending/descending direction).

I tried to check for x.innerHTML.checked==true, but x.innerHTML.checked returns "undefined" so there's no use from this.

Any advice please?




Aucun commentaire:

Enregistrer un commentaire