Javascript Select Form Fields with Chosen

#76 Javascript Select Form Fields with Chosen
4/16/2017

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.
5
rails form javascript ajax view 6:40 min

Summary

Gemfilesource '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' } %>


431201?v=3&s=64
ToniTornado said 2 months ago:

I personally prefer Selectize to Chosen. You can read about the differences here: http://stackoverflow.com/questions/13575531/what-are-the-differences-between-chosen-and-select2

But the usage is very similar and watching the great tutorial helps with using any of the two :-)

635114?v=3&s=64
kobaltz said 2 months ago:

That's strange that a lot of people have such complaints about Chosen. I've been using it for quite some time and never experienced any of the problems that they were describing. I had used Select2 in the past and have nothing against it. Both JS Packages just seem to work. :)

However, I do agree that this episode could have just as easily been swapped with Select2 with minor changes.

Login to Comment