Javascript Select Form Fields with Chosen

Episode #76 by Teacher's Avatar David Kimura

Summary

Chosen is a jQuery plugin that makes long, unwieldy select boxes much more user-friendly. Learn how to use Chosen in a few different ways in this episode; Rails form builder and Simple Form.
rails form javascript ajax view 6:40

Resources

Summary

# Gemfile
source 'https://rails-assets.org' do
  gem 'rails-assets-chosen'
  gem 'rails-assets-chosen-bootstrap' # if using bootstrap
end

# application.js
//= require chosen

...

function chosen_init() {
  $(".chosen-select").chosen().change(
    function(){
      var user = $('option:selected',this);
      var user_url = user.attr('data-url');
      $.getScript(user_url)
    }
  );
}

$(document).on('turbolinks:load', function(){chosen_init()});

# application.css
# if using Bootstrap
 
  *= require chosen-bootstrap

# otherwise, the standard default

 *= require chosen

#  visitors/index.html.erb
   <%= select_tag "users", 
          options_for_select(@users.map{ |user| [user.full_name, user.id, data: { url: edit_user_path(user) }]}), 
          class: 'chosen-select' %>

...

<div id='user_form'></div>

# users/edit.js.erb
$('#user_form').html('<%= j render partial: "form" %>');
// $(".chosen-select").chosen();
chosen_init();

# users/_form.html.erb
<%= f.association :pets, as: :select, multiple: true, input_html: { class: 'chosen-select' } %>