简体   繁体   中英

Error when i try to use select 2 in rails 6

I'm trying to use select2 in rails 6 by the gem select2-rails.

I already add in gemfile gem "select2-rails" and run the bundle and yarn add select2 and inport on.js require("select2") but when I try to use i get this error

$(...).select2 is not a function

how I slove this?

Here's are the steps which you can follow to setup select2 in Rails 6:

  1. Install Webpacker in your Rails project properly, per the project README. If you're starting with a Rails 6 app, this will be done by default.

  2. Add both jquery and select2 :

     yarn add jquery select2
  3. Add a select box to the DOM

     <select class="js-states" name="state"> <option value="AL">Alabama</option>... <option value="WY">Wyoming</option> </select>
  4. Import jquery, select2 and select2 css and apply to the select box when the page is loaded:

     import $ from 'jquery' import 'select2' import 'select2/dist/css/select2.css' window.addEventListener('DOMContentLoaded', () => { $('.js-states').select2() })
  5. For development, set compile: true in config/webpacker.yml . Running the webpack-dev-server is optional.

For more you can also check this demo: https://github.com/rossta/rails6-webpacker-demo/compare/example/select2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM