Tiit Remmel Tiit Remmel - 1 month ago 16
jQuery Question

Randomize table cells

I know its sounds bit wired, but is there any way to randomize table content? precisely cells.
The purpose of this - I have a table generated from several xml's and each xml consists at least 5 items. In main table i can only order them as they are but i need to randomize the items.

For example - jsfiddle.net/tiitremmel/qcSNz/1/

and the result of this table could look randomized td's

Answer
   shuffle($("table"));


    function shuffle(tbl) {
        var arr = tbl.find("td");
        for(
          var j, x, i = arr.length; i;
          j = parseInt(Math.random() * i),
          x = arr[--i], arr[i] = arr[j], arr[j] = x
        );

        var tmp;
        var rows = tbl.find("tr").length

        var cols = tbl.find("tr:first td").length

        for (i = 0; i < rows; i++){
            tmp = tbl.find("tr").eq(i);
            tmp.html()
            for (j = 0; j < cols; j++)
                tmp.append(arr[i*cols+j]);

        }       
  }

Definitely, this is not the best code, this is only approach. But it works. In your case you need to use

shuffle($("table tbody"));
Comments