< mockra >

jQuery Selectable - 18 Apr 2012

Sending selected elements to your Rails application can be pretty simple when using jQuery-ui. You’ll want to make sure you’ve included //= require jquery-ui in your application.js file.

You’ll then want to add a selectable class or id to the list you want to use, or whatever class name you prefer. Make sure to add the values you want passed to your controller to each li element as well. The following coffeescript code will then let you pass the selected information to your application on a button click.

jQuery ->
  $( '#selectable' ).selectable()
  $( 'button.send' ).click ->
    contacts = []
    $( 'li.ui-selected' ).each ->
      contacts.push( $( this ).attr( 'id' ) )
    $.post( $( this ).attr( 'url' ), { contacts: contacts } )

My specific code is being used for a contact box. I’m adding the ids of selected contacts to an array, and then sending those ids to the send_mail controller action. Here’s an example of the post paramaters: Parameters: {"contacts"=>["9", "4", "1", "2", "3", "5", "6", "7", "8"]}

As you can see, this specific application sets the post url through an attribute on the button. It’s also storing the contact’s id in an li attribute. You can style selected li elements in your css using the ui-selected class.

I don’t have much experience with javascript or jQuery, but I’d be happy to attempt to answer any questions, so feel free to contact me if you get stuck. Feedback is always more than welcome too.