DEV Community

Cover image for Rails 6, Stimulus and Select2
Ronak Bhatt for Main Street

Posted on • Updated on

Rails 6, Stimulus and Select2

This is just a quicky, to help out anyone using Rails 6, or any Stimulus-enabled Rails project and Select2, the amazing jQuery plugin for better select boxes.

add select2 & select2-bootstrap-theme package in web-pack
yarn add select2
yarn add select2-bootstrap-theme
Enter fullscreen mode Exit fullscreen mode
Simple Select2 + Stimulus Controller

select2_controller.js

import { Controller } from "stimulus"
import $ from 'jquery';

require("select2/dist/css/select2")
require("select2-bootstrap-theme/dist/select2-bootstrap")

import Select2 from "select2"

export default class extends Controller {
  connect() {
    $('.content-search').select2();
  }
}
Enter fullscreen mode Exit fullscreen mode
Replace f.select dropdown according to select2 specifications
<div class="form-group" data-controller='select2'>
  <%= f.select :user_id, User.all.map { |user| user.name }, {include_blank: false, required: true, include_hidden: false}, class: 'form-control content-search' %>
</div>
Enter fullscreen mode Exit fullscreen mode

I hope that helps someone. Thanks :).

I’d love to hear thoughts or comments around this. Feel free to email me at ronakabhattrz@gmail.com or hit me up on Twitter, @ronakabhattrz.

Top comments (7)

Collapse
 
justinmcodes profile image
jmarsh24

Could you add to this guide how to fire native events with select2?

Collapse
 
ronakabhattrz profile image
Ronak Bhatt

You can do bro please chek this Link for Select2 Events

Collapse
 
justinmcodes profile image
jmarsh24

I figured out how.

.on("select2:select", function() {
let event = new Event('change', { bubbles: true })
this.dispatchEvent(event)

I was just asking because I think it might be useful for the guide.

Thread Thread
 
ronakabhattrz profile image
Ronak Bhatt

Great will DO it Thanks :) 😊

Collapse
 
seanmsmith23 profile image
Sean Smith

Thanks for this! I've tried a bunch of variations of this without success and this finally works!

Collapse
 
ronakabhattrz profile image
Ronak Bhatt

Thanks a lot, man. 👨 🚀 keepcoding.

Collapse
 
justinmcodes profile image
jmarsh24

You wouldn’t happen to have any advice on forcing the dropdown menus to always stay down with stimulus would you?

It’s not supported by select2.