Reputation: 868
What is the right way to add the allowClear
option to the select2 widget in my view?
$ ->
$("#practice_toolkeeper").select2().select2('val',$("#toolkeeper_value").val())
I have the following code in my view:
<%= f.select :toolkeeper, options_from_collection_for_select(@people, :id, :name), :prompt => "Select type question" %>
Which generates this HTML:
<select id="practice_toolkeeper" name="practice[toolkeeper]">
<option value="">Select type question</option>
<option value="21">sdifj</option>
<option value="20">maxam</option>
<option value="22">maxab</option>
<option value="19">maxa</option>
<option value="23">dafuq</option>
<option value="15">bla</option>
<option value="24">asdasdasd</option>
<option value="13">abl</option>
<option value="17">Testa</option>
</select>
I've tried many variations, but none is working yet...
Upvotes: 3
Views: 2464
Reputation: 769
For My Developer Fellas Landed here
Suppose You are using Formtastic Normally with Active Admin You can pass during declaration
f.input :your_select_2_field, { as: :select2, collection: ['a', 'b'], include_blank: 'Select Nothing'}
Concentrate On Curly Braces {}
-Happy Coding :)
Upvotes: 0
Reputation: 126082
You need to do a few things to get this to work:
Set the allowClear
and placeholder
options in an options object that you use when initializing the widget:
$ ->
$("#practice_toolkeeper")
.select2({
allowClear: true,
placeholder: 'Select type question'
})
.select2('val',$("#toolkeeper_value").val())
It looks like the allowClear
option only works when there's an empty option
in the select
. To generate an empty option you could use {:include_blank => true}
when generating the select:
<%= f.select :toolkeeper, options_from_collection_for_select(@people, :id, :name), {:include_blank => true} %>
Basically you want your HTML to look like this:
<select id="practice_toolkeeper" name="practice[toolkeeper]">
<option value=""></option>
<option value="21">sdifj</option>
<!-- etc -->
</select>
Example: http://jsfiddle.net/Z63d7/
Upvotes: 5