musings

February 21, 2008

Sortable list with jQuery and Coldfusion

Filed under: ColdFusion, jQuery — aliaspooryorik @ 2:17 pm
Tags:

jQuery has a really nice plugin called “sortable” that lets you reorder a list using drag and drop. It’s really easy to get it up and running. In your display page you would have:

<cfoutput>

<ul id="sortable">
  <cfloop query="qrySections">
    <li id="section_id_#qrySections.section_id#">#qrySections.section_title#</li>
  </cfloop>
</ul>

<form action="#CGI.SCRIPT_NAME#" method="post" id="frm-sort">
  <input type="submit" name="save" id="save" value="save" />
  <input type="hidden" name="sort_serialized" id="sort_serialized" value="" />
</form>

</cfoutput>

<script type="text/javascript">
<!-- <![CDATA[
$(function(){
  $.getScript("js/jquery.dimensions.js", function(){
    $.getScript("js/ui.mouse.js", function(){
      $.getScript("js/ui.draggable.js", function(){
        $.getScript("js/ui.droppable.js", function(){
          $.getScript("js/ui.sortable.js", function(){
            // required plugins have all loaded
            $("#sortable").sortable({});
          });
        });
      });
    });
  });
});
$('#frm-sort').submit(function(){
  $('#sort_serialized').val($('#sortable').sortable('serialize'));
});
// ]]> –>
</script>
<noscript>Please enable javascript to sort sections</noscript>

Then in your Coldfusion script that handles the form submission:

<cfif StructKeyExists(attributes, "sort_serialized")>

  <cfset variables.lst_section_id = ReReplaceNoCase(attributes.sort_serialized, "(&){0,1}section_id\[\]=”, “,”, “all”) />

  <cfloop from=”1″ to=”#ListLen(variables.lst_section_id)#” index=”index”>

    <cfquery name=”qryOrder” datasource=”#Application.Datasource#”>
      update [Sections] set
        section_order = <cfqueryparam value=”#index#” cfsqltype=”cf_sql_integer” />
      where section_id = <cfqueryparam value=”#ListGetAt(variables.lst_section_id, index)#” cfsqltype=”cf_sql_integer” />
    </cfquery>

  </cfloop>

</cfif>

That’s it. To get the jQuery files visit http://ui.jquery.com/

2 Comments »

  1. Why won’t this work with tr’s without dumping in a UL or div or span??

    Comment by Kevin Quillen — February 27, 2008 @ 2:45 am

  2. Hi Kevin - it won’t work with a table because you have the td tag inside the tr. If you want to sort table rows have a look at http://www.isocra.com/2008/02/table-drag-and-drop-jquery-plugin/

    Comment by aliaspooryorik — February 27, 2008 @ 4:21 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.