Clear Select2 Search Input When No Results Found

177 Views Asked by At

I am using jQuery Select2 version 4.0.13. I would like to auto clear the search text box when the No Results Found displays. Sort of a reset of the dropdown options. Currently I use scanned barcodes that match the dropdown option values. If I scan in a barcode that is not in the list the scanned barcode text remains in the search display. Then if I scan in an acceptable barcode it just appends to the end of what ever is in the search text box. If I manually clear the search text box it will work as expected. I have the following code but where the alert is I need to have syntax to clear the search text thus resetting to dropdown options.

$('.packageDropDown').select2({
    dropdownCssClass: 'ui-widget ui-jqdialog zclass',
    width: 350,
    "language": {
        "noResults": function(searchedTerm) {
            alert("No Match");

        }
    }
});
1

There are 1 best solutions below

5
Kiran Shahi On

In noResults, remove the value from .select2-search__field with $('.select2-search__field').val(''); and trigger the input event.

$('.packageDropDown').select2({
  dropdownCssClass: 'ui-widget ui-jqdialog zclass',
  width: 350,
  "language": {
    "noResults": function(searchedTerm) {
      $(".packageDropDown").val("AL").trigger("change");
      $(".select2-search__field").val("").trigger("input");
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
<select class="packageDropDown" name="state">
  <option value="AL">Alabama</option>
  <option value="WY">Wyoming</option>
</select>