musings

February 27, 2008

Sorting table rows with jQuery and ColdFusion

Filed under: ColdFusion, jQuery — aliaspooryorik @ 10:08 pm

I posted a drag and drop example of sorting and saving a list using the jQuery sortables plugin. I was asked how this could be done with table rows. The jQuery TableDnD plugin comes to the rescue!

It doesn’t have serialize method so you need to get the new order yourself which can be done easily by looping through the rows and building a list in the correct order.

<html>
<head>
<script type="text/javascript" src="js/jquery-1.2.3.min.js"></script>
<script type="text/javascript" src="js/jquery.tablednd.js"></script>
<script type="text/javascript">
<!-- <![CDATA[
$(function(){
  $("#sortable-tbl").tableDnD();

  $('#frm-sort').submit(function(){
    var sRowOrder = "";
    $("#sortable-tbl tr").each(function(i,o){
    if (sRowOrder.length) {
      sRowOrder += "," + o.id;
    } else {
      sRowOrder = o.id;
    }
    });
    $('#sort_order').val(sRowOrder);
  });
});
// ]]> –>
</script>
</head>
<body>

<table id=”sortable-tbl”>
    <tr id=”section_id_1″>
    <td>One</td>
    <td>Row A</td>
  </tr>
  <tr id=”section_id_2″>
    <td>Two</td>
    <td>Row B</td>
  </tr>
  <tr id=”section_id_3″>
    <td>Three</td>
    <td>Row C</td>
  </tr>
  <tr id=”section_id_4″>
    <td>Four</td>
    <td>Row D</td>
  </tr>
</table>

<form id=”frm-sort”>
  <input type=”submit” name=”save” id=”save” value=”save” />
  <input type=”hidden” name=”sort_order” id=”sort_order” value=”" />
</form>

</body>
</html>

* UPDATE *

Someone asked how to update the database using ColdFusion, so here is the code:

<!--- strip the 'section_id_' from the list, so that we only have a list of ids --->
<cfset form.sort_order = ReplaceNoCase(form.sort_order, "section_id_", "", "all") />

<cfloop from="1" to="#ListLen(form.sort_order)#" index="ndx">
  <cfquery name="qryOrder" datasource="#Request.Datasource#">
    update [Sections] set
      section_order = <cfqueryparam value=”#ndx#” cfsqltype=”cf_sql_integer” />
    where section_id = <cfqueryparam value=”#ListGetAt(form.sort_order, ndx)#” cfsqltype=”cf_sql_integer” />
  </cfquery>
</cfloop>

1 Comment »

  1. Thanks for the code for updating db records with ColdFusion!

    Rick

    Comment by Rick Faircloth — March 18, 2008 @ 4:24 pm

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.