< スポンサーリンク >
テーブルの行をドラッグで並べ替える
テーブルの行をドラッグで並べ替えるサンプルです。
jQuery UIを使ってみます。
並べ替えを開始した時に、結果表示枠に「並べ替えを開始します」と表示し、並べ替えたあとにテーブルの行のidをsort.phpへPOST送信し、結果表示枠にPOST送信したデータを表示しています。
<サンプル>
NO | 項目 |
---|---|
1 | あいうえお |
2 | かきくけこ |
3 | さしすせそ |
4 | たちつてと |
↓結果表示枠
<html>index.html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>テーブル行の並べ替え</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<script src="sort.js"></script>
</head>
<body>
<table>
<thead>
<tr><th>NO</th><th>項目</th></tr>
</thead>
<tbody id="tbl_sort">
<tr id="tr1"><td>1</td><td>あいうえお</td></tr>
<tr id="tr2"><td>2</td><td>かきくけこ</td></tr>
<tr id="tr3"><td>3</td><td>さしすせそ</td></tr>
<tr id="tr4"><td>4</td><td>たちつてと</td></tr>
</tbody>
</table>
<div id="div_result"></div>
</body>
</html>
<style>style.css
table{
margin-bottom: 1.5em;
padding: 0;
border-top: 1px solid #959595;
border-left: 1px solid #959595;
}
tbody tr{
cursor: pointer;
}
th, td{
padding: 0.5em;
border-right: 1px solid #959595;
border-bottom: 1px solid #959595;
}
th{
background-color: #f0f0f0;
font-weight: bold;
text-align: left;
}
<JavaScirpt>sort.js
$(function(){
$("#tbl_sort").sortable({
start: function() {
$("#div_result").html("並べ替えを開始します");
},
update: function() {
var items = $("#tbl_sort").sortable("toArray");
$.post(
"sort.php",
{ postData: items },
function(data){
$("#div_result").html(data);
},
"html"
);
}
});
});
<PHP>sort.php
<?php
print_r($_POST['postData']);
?>
< スポンサーリンク >