Mappa Via Marconi 20, Bussolengo (VR)
Email info@devinterface.com

Ruby on Rails and jQuery: multiselect with checkbox

Today I want to present a very convenient jQuery plugin I’ve used to create a combo box with checkboxes for a multi-selection field.

Suppose we have a form of insertion / modification of user data, and that the user can have multiple functions.
We start with rendering the form with a multi-selection field, where you can select more functions with the combination “<ctrl> + click “.

1
2
3
4
5
6
7
8
9
10
11
12

<%= simple_form_for(@user) do |f| %>
<%= f.label :password %>
<%= f.password_field :password %>

<%= f.label :password_confirmation %>
<%= f.password_field :password_confirmation %>
<%= f.error :password, :class => "formError" %>

<%= f.label :functions %>
<%= select_tag("functions[]", options_for_select(@functions.collect { |ff| [ff.name, ff.id] }, @user.functions.collect { |fs| fs.id }),
{:multiple=>true, :id => "functions"}) %>
<%= f.submit %>

In the above code I used the simple_form plugin to simplify the creation of the form.
The controller will contains something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

class UsersController < ApplicationController

def new
@user = User.new
@functions = Function.all
end

def create
@user = User.new(params[:user])
@user.functions << Function.find(params[:functions]) unless params[:functions].nil?
if @user.save
flash[:notice] = "User created"
redirect_to :action => :index
else
@functions = Function.all
render :action => :new
end
end

end

Now we need some of jQuery to make our form more pleasing.
We download the jQuery UI MultiSelect Widget plugin and then we include it in our pages, such as in the file application.html.erb as follows:

1
2
3

[...]
<%= javascript_include_tag "jquery.multiselect.min" %>
[...]

Finally, simply insert at the end of the page containing the user creation form, the following script:

1
2
3
4
5

<script type="text/javascript">
$(document).ready(function() {
$("#functions").multiselect();
});
</script>

We reload the page and we’ll obtain something like the screenshot below.

This example was tested on a Rails 3 application with JQuery 1.4.2.



Looking for rental properties try real estate alameda.