Clear search term and reload all items of Select2 input after selecting any item
Asked Answered
R

3

5

I have a select2 Input text field in my page in which I am loading items dynamically on focus event of Input field.

When I enter some search text let's say 'vai' then the result items are loaded as 'vaibhav1', 'vaibhav2', 'vaibhav3', 'vaibhav4' with focus on first item. If I press enter key it gets selected.

Now what I want is to clear the search term 'vai' and the items list should be refreshed displayed containing all remaining records including last searched items. Below is my javascript code under $(document).ready(function) for the select2 input field.

function format(item) { return item.name; };
// select2 multiple select feature for Impact Area initialization
var test = $('#impactArea'); 
$(test).select2({
    formatSelection: format,
    formatResult: format ,
    multiple: true,
    width: "612px",
    height: "50px",
    closeOnSelect : false,
    maximumSelectionSize : 20,
    ajax: { 
        type: "GET",
        url: "/progressManagement/testingIssue/impactAreaList",
        dataType: 'json',
        data: function (term) {
          return { q: term };
       },
        results: function (data) {
          return {results: data};
        }
       } ,
       initSelection: function(element, callback) { 
           var rangeList=$('#impactArea').val();
           var id=$(element).val();
            if (id!=="") {
            $.ajax("/progressManagement/testingIssue/selectedImpactArea", {
                data: { rangeList: rangeList },
                dataType: "json"
            }).done(function(data) { 
                callback(data); 
            });
            }
        } 
});

I tried searching in the select2js file to find a function or a flag which could be used for this, please help me if you guys have any ideas about this. Let me know if I am not clear in specifying my requirements or approach. Thanks in advance :)

Rogan answered 15/1, 2015 at 10:21 Comment(3)
Instead of searching in the source code why don't you try the docs? There is an option called allowClear but I don't know if its what you want because isn't clear what you mean about list should be refreshed displayed containing all remaining records including last searched items.Islas
@DontVoteMeDown, basically I want user to be able to select the items with keyboard only (Client requirement), which he can for first item. Next the search text should be removed and all remaining items should be displayed. And I have also gone through the docs.Rogan
@DontVoteMeDown, docs says allowClear resets the value of the select box back to the placeholder (only available when the placeholder is specified). Which is not what I want. I want the selected items to be remain selected, only the search text should be cleared after selection.Rogan
R
7

Somehow I found a workaround, I have cleared the search string using the $(test).select2("search", ""); command whenever the Input field value changes.

$(test).change(function() {
    $(test).select2("search", "");
});

Here, search is the search term variable used in select2.js file which I set to blank string every time user selects or deselects the item in the list. It is working fine for my requirement.

Please let me know if anyone finds a better solution, thanks.

Rogan answered 15/1, 2015 at 12:13 Comment(4)
Does anyone know a way to clear the search results in v4 of select2?Remnant
This worked for a bug of mine also. After un-selecting/deleting a selected option, the search term, which was HTML kept on appearing on the page. I was selecting data with ajax like in the docs: select2.org/programmatic-control/…Pyosis
@Remnant see my answer.Contraband
this answer is not working for select2 v4Ionopause
C
2

In v4, I was able to clear the search field with the following code.

$(test).change(function() {
  $(this).parent().find('.select2-search__field').val("");
})
Contraband answered 1/6, 2021 at 17:57 Comment(1)
The selected answer submits my form. This answer works perfectly.Forebode
T
2

In addition to @Enoch answer, I had to trigger 'input' event after setting the empty value to the search field to reload the options.

$(test).change(function() {
   $(this).parent().find('input.select2-search__field')?.val('').trigger('input');
})
Tonsure answered 3/8, 2022 at 7:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.