0

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!

mRbOneS
  • 121
  • 1
  • 14

1 Answers1

0

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>
Minato
  • 4,383
  • 1
  • 22
  • 28
  • The collection_select cant have more than 6 parameters passed. Its showing an error. I removed :user parameter and tried the code you gave, its not working – mRbOneS Jan 03 '16 at 08:15
  • Forget about the question. How to create a search drop down with contents retrieved from a table. i.e using select2 – mRbOneS Jan 03 '16 at 08:16
  • @saitejareddy can you show the complete code of the view and controller – Minato Jan 03 '16 at 09:51
  • and dude have you included the the `select2-bootstrap-theme` `select2-bootstrap.css` ? – Minato Jan 03 '16 at 09:54
  • @saitejareddy it's in the gem but is it included in your application layout? – Minato Jan 03 '16 at 15:36
  • like mentioned in [README.md](https://github.com/argerim/select2-rails/blob/master/README.md) of the gem. – Minato Jan 03 '16 at 15:37
  • @saitejareddy I made a sample project to test out `select2-rails` myself.. it works perfectly fine.. you can checkout my [repo](https://github.com/mubashir93/select2-test) – Minato Jan 03 '16 at 18:15
  • @saitejareddy you can have a look at `views/posts/_form.html.erb`, `assets/javascript/application.js` and `assets/stylesheets/application.css` and of course the `GemFile`... – Minato Jan 03 '16 at 18:18