Question

The texbox is dynamically filled with a remote call using Select2 and I want to allow users to leave the field blank.

$("#e6").select2({
    placeholder: "Search for a movie",
    minimumInputLength: 1,
    ajax: { 
        url: "http://api.rottentomatoes.com/api/public/v1.0/movies.json",
        dataType: 'jsonp',
        data: function (term, page) {
            return {
                q: term, // search term
                page_limit: 10,
              };
        },
        results: function (data, page) { 
            return {results: data.movies};
        }
    },
 });

Here is working example http://ivaynberg.github.io/select2/index.html#ajax

Was it helpful?

Solution

You can set the allowClear option to true.

$("#e6").select2({
    allowClear: true,
    placeholder: "Search for a movie",
    ...

When set to true, the allowClear option causes the Select2 control to display a clear button, but you must also specify the placeholder option for it to work.

Here's a jsfiddle showing it work for a Select2 that uses ajax.

OTHER TIPS

This worked for me,

$('#f').select2(
  {
    allowClear: true,
    placeholder: {
      id: "-1",
      text:"City",
      selected:'selected'
    },
    data:[
      {id: -1,text: '',selected: 'selected',search:'',hidden:true},
      {    id: 1, 
           text: 'Italy', 
           search: "Italy", 
           children: [
               {id: 2, text: 'Sardinia', search: "Italy Sardinia", selected: false}, 
               {id: 3, text: 'Sicily', search: "Italy Sicily", selected: false}
           ]
      },
      {
          id: 4, 
          text: 'United Kingdom', 
          search: "United Kingdom",
          children:[
              {id: 5, text: 'Guernsey', search: "United Kingdom - Guernsey", selected: false},
              {id: 6, text: 'Jersey', search: "United Kingdom - Jersey", selected: false}
        ]
      }
    ]
  }
);

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 {}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top