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.

Tags: , , , ,


About Claudio

Claudio Marai is a co-founder of DevInterface.

After graduating in Computer Science has contributed to develop complex web applications based on Java/J2EE and desktop applications with the. NET framework for the Ministry of Justice and ultimately for the banking ambit.

The passion for web in recent years has led him to be interested in more modern frameworks such as Ruby on Rails and Django, and to a development approach based on agile methodologies such as eXtreme Programming and SCRUM.

About DevInterface

We are an information and communication technology agency. Our mission is to provide web application development, design services and communication strategies. We specialize in building web applications with modern and efficient frameworks.

Related Post

6 Responses to “Ruby on Rails and jQuery: multiselect with checkbox”

  1. [...] This post was mentioned on Twitter by Ruby on Rails UK, RubyOnRails Ireland. RubyOnRails Ireland said: jQuery and Ruby On Rails: MultiSelect with checkboxes … http://bit.ly/gVpLTP [...]

  2. [...] 使用jQuery在RoR中实现多选框 Share and Enjoy: [...]

  3. b.kidd says:

    So, how do you “preselect” check boxes when a users is editing?

    Example:

    A user has many interests. The first time they submit this form, they check several interests. When they go back to modify their interests, how do I show the current/saved interests as checked in the select list? bare in mind that the list of possible interests is an array, not a relationship. Thanks.

  4. Claudio says:

    Hi, b.kidd.
    If you notice I used an options_for_select within the select_tag.
    It take two parameters, a list of values to display and a list of selected values, according to Ruby on Rails api:
    http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-options_for_select

  5. b.kidd says:

    So I ended up doing this, which worked, although it seems that there should be a more elegant way…

    #view

    {:multiple => true, :class => ‘activities’}, :label=>’What kind of activities do you enjoy?’, :collection => user_activities -%>

    #helper

    def user_activities
    activities = []
    MyModel.activities.map do |activity|
    if @info.activities.present? && @info.activities.include?(activity)
    activities < ‘yes’}]
    else
    activities << [activity]
    end
    end
    activities
    end

  6. b.kidd says:

    Trying some formatting ;-)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #view
    {:multiple => true, :class => ‘activities’}, :label=>’What kind of activities do you enjoy?’, :collection => user_activities -%>
    #helper
    def user_activities
    activities = []
    MyModel.activities.map do |activity|
    if @info.activities.present? && @info.activities.include?(activity)
    activities < ‘yes’}]
    else
    activities << [activity]
    end
    end
    activities
    end

Leave a Reply

Insert code beetween <code lang="ruby"> and </code>

Copyright 2012 DevInterface s.n.c.

DevInterface Blog is proudly powered by WordPress