How to allow user to select empty string on Select2

Smith picture Smith · Mar 14, 2014 · Viewed 48.4k times · Source

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

Answer

John S picture John S · Mar 14, 2014

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.