JQuery UI: Sortable

Enable a group of DOM elements to be sortable. Click on and drag an element to a new spot within the list, and the other items will adjust to fit. By default, sortable items share draggable properties.

<style>
  #sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
  #sortable li { margin: 0 3px 3px 3px; padding: 0.2em; padding-left: 1.5em; height: 18px; background-color: #ccc; cursor: pointer }
  #sortable li:hover { background-color: #FF6600; }
  #sortable li:hover a { color: white; }
</style>
<script>
  $(function() {
    $(".submitButton").click(function() {
      // Serializes the sortable's item id's into an array of string
      var items = $("#sortable").sortable('toArray');
      var data = new Object();
      for (index in items) {
        data['sorted_' + index] = items[index];
      }
 
      $.post('http://www.yourdomain.com?action=savesort', data, function(succes) {
        if (succes.succes) {
	  $("#status").html('Sort saved');
	  setTimeout(function() { $("#status").html(""); }, 5000);
	} else {
	  alert("Error: sort not saved.");
	}
      }, "json");
 
      return false;
    });
 
    $("#sortable").sortable();
    $("#sortable").disableSelection();
  });
</script>
<div id="status"></div>
<form action="#" name="form">
  <ul id="sortable">
    <li id="10">Test 1</li>
    <li id="30">Test 3</li>
    <li id="20">Test 2</li>
  </ul>
  <input type="submit" value="Save sort" class="submitButton" />
</form>
foreach ($_POST as $key=>$id) {
  if (strpos($key, 'sorted') !== false) {
    $key = explode('_', $key);
    $sort = $key[1];
    $sql = "UPDATE table SET sort=" . $sort . " WHERE id=" . $id;
    $result = mysql_query($sql);
  }
}
 
$succes['succes'] = true;
echo json_encode($succes);

Leave a Reply