Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow user to select empty string on Select2

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

like image 362
Smith Avatar asked Mar 14 '14 16:03

Smith


People also ask

How do I make Select2 empty?

In order to clear the selection of those values which are selected using a Select2 drop down,we can use the empty() function. The dropdown can be reset using Jquery. $("#select2_example"). empty();

How do I add options in Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data. text, data.id, false, false); $('#mySelect2'). append(newOption).

What is initSelection in Select2?

In the past, Select2 required an option called initSelection that was defined whenever a custom data source was being used, allowing for the initial selection for the component to be determined. This has been replaced by the current method on the data adapter.


1 Answers

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.

like image 154
John S Avatar answered Sep 29 '22 21:09

John S