Web Development with jQuery®

(Elliott) #1

(^354) ❘ CHAPTER 13 SORTABLE


Saving the State of Sorted Lists


The Sortable API in jQuery UI wouldn’t be complete without one last detail: saving the state of a
sorted list. This too is covered by the Sortable plugin. In Chapter 7, “AJAX,” you learned about
jQuery’s serialize() method, which automatically takes a selection of input elements for a form and
serializes the data in those input elements into a string of data that you can then submit to a server-
side script with an AJAX request. The Sortable plugin provides a similar mechanism for retrieving
data from a sortable list. But instead of retrieving input form values, the Sortable plugin retrieves a
specifi c attribute from each sortable element. By default, the Sortable plugin retrieves the value of the
id attribute. In the context of the examples you’ve completed in this chapter, you’d give each <li>
element an id attribute and then use the Sortable plugin’s mechanism for serializing the data present
in each id attribute into a string that you can pass on to an AJAX request to a server-side script, so
you can save the sort. The following code snippet shows the code you’d use on the JavaScript side:

var data = $('ul').sortable(
'serialize', {
key: 'listItem[]'
}
);

In the preceding code, to serialize the data present in the id attribute of each <li> element, you call
the sortable() method, with the fi rst argument set to 'serialize'. For the second argument, you
specify an object literal of options, which decide how the serialization will be done. The key option
specifi es the name you want to use for each query string argument. The name listItem[] is used,
which in PHP and some other server-side scripts will cause the query string of sorted items to be
translated into an array or hash.

In the following example you apply the concepts you’ve just learned to the sortable fi les example
that you’ve been working on throughout this chapter. Using Example 13-2.html as the basis, copy
the contents of that fi le into a new document, and save that document as Example 13-3.html; then
add a data-path attribute to each <li> element, as you see in the following markup. Don’t forget to
update each fi le reference to Example 13-3.

<!DOCTYPE HTML>
<html xmlns='http://www.w3.org/1999/xhtml'>
<head>
<meta http-equiv='content-type'
content='application/xhtml+xml; charset=utf-8' />
<meta http-equiv='content-language' content='en-us' />
<title>Sortables</title>
<script src='../jQuery.js'></script>
<script src='../jQueryUI.js'></script>
<script src='Example 13-3.js'></script>
<link href='Example 13-3.css' rel='stylesheet' />
</head>
<body>
<div id='finderCategoryFileWrapper'>
<ul id='finderCategoryFiles'>
<li class='finderCategoryFile'
data-path='/Blog/apple/CoreImage.html'>
<div class='finderCategoryFileIcon'></div>
<h5 class='finderCategoryFileTitle'>

http://www.it-ebooks.info

Free download pdf