问题
I'm trying to implement select 2 using the select2-rails gem but I'm not familiar with jQuery or rails.
I basically tried to copy the placeholder example from this website and adapt it to my needs:
http://rails-select2-example.herokuapp.com/
I have a field which lists performers for an event. Originally I just had a simple text field for :performer. But I'd like replace this with a lookup based on my users profile_name which I can then assign to the :performer field.
So I have something like this:
<%= select_tag "performer", options_from_collection_for_select(@user, "id", "profile_name"), include_blank: true, id: "performer", data: { placeholder: "Choose a performer" } %>
Followed by this:
<script type="text/javascript"> $(document).ready(function() {
$('select#performer').select2({
placeholder: "Choose a performer",
allowClear: true
});
});
</script>
Which works and gives me a dropdown of the users. But I'm not sure how to pass this information to the :performer field. This is probably really simple, so much so that whenever I've searched for simple2 nowhere seems to mention how you pass it to the field. Please help!
Update1:
I can get it to submit by using the following BUT it becomes a simple select box rather than being a select2 autocomplete box.
<%= f.select_tag "performer", options_from_collection_for_select(@user,
"profile_name", "profile_name"), include_blank: true, id: "performer", data:
{ placeholder: "Choose a performer" } %>
Update2:
Got it to work but still cannot get the placeholder to display.
<%= f.select :performer, options_from_collection_for_select(@user,
:profile_name,:profile_name), {}, include_blank: true,
id: "performer", data: { placeholder: "Choose a performer" } %>
回答1:
Instead of writing data:{placeholder:"Choose a performer"} prefer writing directly after the comma placeholder: "placeholder value" in my opinion it should work .
来源:https://stackoverflow.com/questions/22461438/select2-rails-passing-data-to-form-field