Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jQueryUI sortable list with forms

I'm using jQueryUI to create a sortable list, and the UI part works great in that I can sort the items as desired on the web page. I can't figure out, though, how the order of the sorted list is included in the POST. I'm a total noob with javascript so please forgive me if this is really simple.

Here are the relevant portions of my html:

<script type="text/javascript">
  google.load("jquery", "1");
  google.load("jqueryui", "1");
  function OnLoad(){
    $( "#sortable" ).sortable({ axis: "y", containment: "#ballot", scroll: false });
    $( "#sortable" ).disableSelection();
  }
  google.setOnLoadCallback(OnLoad);
</script>

[...]

<form method="POST" action="/vote">
<input type="hidden" name="key" value="{{ election.key }}">
<input type="hidden" name="uuid" value="{{ uuid }}">
<div id="ballot" class="center">
<ol id="sortable" class="rankings">
  <li class="ranking">Jamie</li>
  <li class="ranking">Joanie</li>
  <li class="ranking">Morley</li>
  <li class="ranking">Frank</li>
  <li class="ranking">Larry</li>
</ol>
</div>
</form>

How can the order of Jamie, Joanie, Morley, Frank, and Larry be encoded in the POST?

like image 573
gaefan Avatar asked Feb 27 '11 04:02

gaefan


2 Answers

You can use the method .serialize on your sortable object : http://docs.jquery.com/UI/Sortable#method-serialize

$( "#sortable" ).sortable('serialize') will give you an ajax submittable array of items. Just assign it to an input box if you are not using ajax. Or simply pass it into your data array if using ajax

EDIT Example here : http://jsfiddle.net/jomanlk/KeAer/2/

As the jquery docs note, for this to work your elements need to have ids in the form of set_number (e.g. rank_1, rank_2). So I've modified your HTML

Just remove the return false in the form and the serialized value will be set to the input box on form submission

like image 183
JohnP Avatar answered Oct 16 '22 03:10

JohnP


Another option is to just have a hidden input form field with the ID value for the item as the value and the same name. Then submit the form after sorting stops. The values will all be available in the posted data in the order they were after the sort.

I do something like this:

$(".sortable").each(function () {
    $(this).sortable({
        update: function (event, ui) {
            $(this).closest("form").trigger("onsubmit");
        }
    });
});

And the form looks like this:

<form ...>
<ul class="sortable">

        <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Some info here<input id="id_name" name="id_name" type="hidden" value="1" /></li>

        <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Some more info<input id="id_name" name="id_name" type="hidden" value="2" /></li>

</ul>
</form>
like image 25
Doug Lampe Avatar answered Oct 16 '22 01:10

Doug Lampe