Search code examples
jqueryjquery-select2

Select2 custom search (allow only numeric input in search)


I have a select box having numbers in dropdown, i need to search the values but only allow numeric inputs while searching.

For example.

Select box values includes

1234

2345

7656

currently my select2 search box accepts both alphabets and numbers. I need it to accept only numeric inputs.

<select class="js-example"  placeholder="Select">
   <option value="1">1234</option>
   <option value="2">2345</option>
   <option value="3">7656</option>
</select>

<script>
  $('.js-example').select2();
</script>

Solution

  • This got resolved now using below code

    $(".select2").select2({
      tags: true,
      placeholder: "de",
      allowClear: true
    });
    
    $(document).on('keypress', '.select2-search__field', function() {
      $(this).val($(this).val().replace(/[^\d].+/, ""));
      if ((event.which < 48 || event.which > 57)) {
        event.preventDefault();
      }
    });