Select 2 in Rails not rendering properly

2019-09-05 02:02发布

I am trying to implement select2 functionality in my project. It is not rendering properly. I am pasting my code, please tell me where it went wrong

<div class="form-group">
              <label for="userInputCollegeName">College Name</label>
              <%= f.collection_select(:college_id, College.all, :id, :name, {:prompt => 'Select the college'}) %>
            </div>



<script>$(document).ready(function() {
  $("#user_college_id").select2({theme: "bootstrap"});
});</script>

In my html the id for the collection_select is user_college_id.

I am adding an image:

enter image description here

I know that the first select is because of collection_select tag and the second field is because of select2, but I dont need the first one.

I only require the select2 field. How can we do that? Any help is appreciated thankyou!

1条回答
再贱就再见
2楼-- · 2019-09-05 02:14

there might be problem in your

f.collection_select(:college_id, College.all, :id, :name, {:prompt => 'Select the college'})

try changing it to

f.collection_select(:college_id, College.all, :id, :name, {:prompt => 'Select the college'}, {class: "user-college-select"})

and inside your javascript:

<script>
   $(document).ready(function() {
      $(".user-college-select").select2({theme: "bootstrap"});
   });
</script>
查看更多
登录 后发表回答