submit a sortable_element in a form

Today I needed to use some of Scriptaculous’ nifty sortable_elements inside of a larger form for a rails app I’m working on. The way I did it works, but it is doubtlessly a terrible hack. Whatever.

Being a complete javascript newb, I took my cue from this post on the rails mailing list which unfortunately, as the guy requested, did not have the answer bundled up nice and neatly for me. On the other hand, it was pretty easy to do by updating a hidden field with the sortable_elements to get the data submitted with the form. Onward with an example…

In my particular case, I have two lists which I drag and drop between with sort order being important in the destination list. These sortable elements are part of a form which the user will post to the app. In my form rhtml template, I have a submit_tag like so:
<%= submit_tag("Add", :onclick => 'sortableToHidden()') %>

The layout for the template in question has a small snippet of javascript:

function sortableToHidden() {
  document.my_form_name.sortable_hidden.value = \\
    Sortable.sequence('my_sortable_list_id');
}

Where:

  • ‘my_form_name’ is the name of the form within which I want to submit the data
  • ’sortable_hidden’ is the name the hidden field in the form
  • ‘my_sortable_list_id’ is the id given to my sortable list in the sortable_element helper

That’s pretty much it. You can then easily access your sorted list via params[:sortable_hidden].

I’m sure there’s some much more nifty, magical way of doing this (which I would love to hear about) but this gets the job done.

Comments

Leave a Reply