Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
4
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@yambejp

[test020] テーブル横ソート

テーブル横ソート

仕様

tbodyの1列目をクリックすると、右側の表を横方向にソートする

ソース

javascript

test020.js
$(function(){
  $('#t1 tbody td').filter(function(){
    return $(this).closest('tr').find('td').index(this)==0;
  }).on('click',function(){
    var list=$(this).siblings('td').map(function(x){return {idx:x+1,num:parseInt($(this).text())}}).get();
    list.sort(function(x,y){
      if(x["num"]==y["num"]) return 0;
      return x["num"]>y["num"]?1:-1;
    });
    $(this).closest('table').find('tr').each(function(){
      var self=$(this);
      list.forEach(function(x){
        self.find('td,th').eq(x["idx"]).clone().appendTo(self);
      });
      self.find('td,th').filter(':gt(0):lt('+list.length+')').remove();
    });
  });
});

HTML

test020.htm
<html>
<head>
<title>テーブル横ソート</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="test020.js"></script>
</head>
<body>
<h1>テーブル横ソート</h1>
<h2>tbodyの1列目をクリックすると、右側の表を横方向にソートする</h2>
<table id="t1">
<thead>
<tr>
<th data-type="string">名前<span></span></th>
<th data-type="integer">国語<span></span></th>
<th data-type="integer">数学<span></span></th>
<th data-type="integer">保健<span></span></th>
<th data-type="integer">社会<span></span></th>
<th data-type="integer">美術<span></span></th>
<th data-type="integer">英語<span></span></th>
</tr>
</thead>
<tbody>
<tbody>
<tr class="dothesort">
<td>鈴木</td><td>12</td><td>19</td><td>25</td><td>25</td><td>89</td><td>25</td>
</tr>
<tr class="dothesort">
<td>高橋</td><td>25</td><td>89</td><td>25</td><td>25</td><td>89</td><td>25</td></tr>
</tr>
<tr class="dothesort">
<td>佐藤</td><td>60</td><td>987</td><td>89</td><td>25</td><td>89</td><td>25</td>
</tr>
<tr class="dothesort">
<td>山田</td><td>604</td><td>78</td><td>25</td><td>25</td><td>89</td><td>25</td>
</tr>
</tbody>
</table>
</body>
</html>

その他

サンプル

-CodePen

See the Pen test020 by yambe jp (@yambejp) on CodePen.

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
4
Help us understand the problem. What are the problem?