3

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...

4

2 回答 2

5

You need to do a few things to get this to work:

  1. 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())
    
  2. 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/

于 2013-03-31T00:45:10.207 回答
0

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 :)

于 2015-12-08T14:25:53.007 回答