背景
ユーザーにより自分が好きな順番でtableの表示データーを設定できるように
jQuery UI
のsortable
を使用してHTMLのtable項目の並び順設定を作ってみました。
結果
環境
- jQuery:
1.8.3
- jQuery UI:
1.8.24
今回試したブラウザ
以下はテストしてみたブラウザのリストです。これ以外のブラウザにも対応できるかもしれません。
- Mozilla Firefox:
103.0.2
- Chrome:
104.0.5112.79
- Microsoft Edge:
104.0.1293.47
- Safari:
15.6
ソースコード
並び替えたいHTMLのtableを用意する
html
<table id="tblLocations" cellpadding="0" cellspacing="0" border="1">
<tr>
<th>ID </th>
<th>色</th>
<th>並び替え</th>
</tr>
<tr>
<td>1</td>
<td>Red</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>Green</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>Blue</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>Yellow</td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td>Purple</td>
<td>5</td>
</tr>
</table>
jQueryとjQueryUIを読み込む
html
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.24/jquery-ui.min.js"></script>
jQuery UI Sortableプラグインの設定
html
<script type="text/javascript">
$(function () {
$("#tblLocations").sortable({
// 見出しである一番上の行以外をドラッグできるように設定
items: 'tr:not(tr:first-child)',
// マウスカーソルの形状を変える
cursor: 'pointer',
// ドラッグできる方向は縦方向のみなのでaxisに(y)を設定
axis: 'y',
// ドラッグされた行が明確に見えるようにstartイベントにselectedクラスを設定
start: function (e, ui) {
ui.item.addClass("selected");
},
// ドロップした行のselectedクラスを解除して並び替え列を更新
stop: function (e, ui) {
ui.item.removeClass("selected");
$(this).find("tr").each(function (index) {
// index = 0は見出しの行ですから更新しない
if (index > 0) {
$(this).find("td").eq(2).html(index);
}
});
}
});
});
</script>
デザインの為CSSを用意する
html
<style type="text/css">
table
{
border: 1px solid #ccc;
border-collapse: collapse;
}
table th
{
background-color: #F7F7F7;
color: #333;
font-weight: bold;
}
table th, table td
{
width: 100px;
padding: 5px;
border: 1px solid #ccc;
}
.selected
{
background-color: #54C500;
color: #fff;
}
</style>
感想
ドラッグ&ドロップで並び替えの機能は難しいと思いましたが、実際にやってみるとjQuery UI Sortableプラグインは分かりやすくて想像より簡単でした。