select2 超好用的下拉選單
阿新 • • 發佈:2019-01-27
Rails 自帶的下拉選單不好用,效果一般,流行的 select2 就好用多了。
參考連結:
注意
從 Rails5.1 版本開始,Gemfile 預設不再安裝 gem 'jquery-rails'
,無法正常使用 select2,解決方法如下:
在 Gemfile 加入 gem 'jquery-rails'
終端 bundle install
重啟 rails s
修改檔案 app/assets/javascripts/application.js
- //= require rails-ujs
+ //= require jquery
+ //= require jquery_ujs
select2 簡單教程
在 Gemfile 加入 gem 'select2-rails'
終端 bundle install
重啟 rails s
檔案 app/assets/javascripts/application.js 最下方新增程式碼
//= require select2
檔案 app/assets/stylesheets/application.scss 最下方新增程式碼
@import "select2";
@import "select2-bootstrap";
從 User 表中實現單選與多選(省略 User 表的相關建立)
<%= form_for @letter_text do |f| %>
<p>
<%= f.label "收件人" %>
<!-- 使用者.多選框 -->
<%= select_tag :rec_id, options_for_select(User.all.collect{|a| [a.name, a.id]}), class: "form-control" ,multiple: "true"%>
</p>
<p>
<%= f.label "發件人" %>
<!-- 使用者.單選框 -->
<%= select_tag :send_id, options_for_select(User.all.collect{|a| [a.name, a.id]}), class: "form-control"%>
</p>
......#省略無關程式碼
<% end %>
</div>
<script>
// 多選框樣式
$("#rec_id").select2({
theme: "bootstrap"
})
</script>