脳汁portal

アメリカ在住(だった)新米エンジニアがその日学んだIT知識を書き綴るブログ

tablesorterでpager機能を使う方法

以前のポストでtablesorterの基本機能であるsort機能とfilter機能を説明しましたが、今回はpager機能を利用する方法を説明します

基本機能(sort & filter機能の使い方)

portaltan.hatenablog.com

Pagerの使い方

1.まずはsortだけ可能な単純なtableを作成します

html

<table class="pager-table">
  <thead>
    <tr>
      <td>column1</td>
      <td>column2</td>
    </tr>
  </thead>
  <tbody>
    <% 30.times{|t| %>
      <tr>
        <td><%= t %></td>
        <td><%= t %></td>
      </tr>
    <% } %>
  </tbody>
</table>

javascript

$('table.pager-table')
  .tablesorter({})
}

f:id:portaltan:20150928170835p:plain

2. tablesorter pluginの"jquery.tablesorter.pager.js"をダウンロードして読み込みます

http://mottie.github.io/tablesorter/addons/pager/jquery.tablesorter.pager.js

Railsの場合(app/assets/javascripts/application.js)

//= require jquery-2.1.1.min
//= require jquery.tablesorter.combined.js
//= require jquery.tablesorter.pager.js
3. pager機能を利用するために、まずはスライダーを作成します

html

  <div class="pager">
    <button type='button' class='first'>&lt;&lt;</button>
    <button type='button' class='prev'>&lt;</button>

    <span class="pagedisplay" value=""/>
    <input type="text" class="pagedisplay"/>

    <button type='button' class='next'>&gt;</button>
    <button type='button' class='last'>&gt;&gt;</button>

    <select class="pagesize">
      <option value="10">10</option>
      <option value="20">20</option>
      <option value="30">30</option>
    </select>
  </div>

これで以下のスライダーが出来ました
f:id:portaltan:20150928172502p:plain

4. 次にこのスライダーとPager機能を利用する記述をjsファイルに書きます
$('table.pager-table')
.tablesorter({})
.tablesorterPager({
    container: $(".pager"),
});

これで基本の設定は完了です。
以下のようにpager機能が反映されます。
f:id:portaltan:20150928173047p:plain

確認

「>」ボタンを押すとテーブルの内容が次Pageへと変わります。

f:id:portaltan:20150928173220p:plain

「<<」ボタンを押すと最初に戻ります

f:id:portaltan:20150928173357p:plain

プルダウンで一度に表示させる行数を変更できます。

f:id:portaltan:20150928173439p:plain

Tips

デフォルトで表示させる行数を変更したい場合

javascript

$('table.pager-table')
.tablesorter({})
.tablesorterPager({
    container: $(".pager"),
    size: 10,  //<==表示させたい行数を指定
});

html

<select class="pagesize">
  <option value="10">10</option>
  <option selected="selected" value="20">20</option> <!-- プルダウンもdefaultを変更 -->
  <option value="30">30</option>
</select>