skip to Main Content
<select class="" id="js-select2" multiple="multiple">
          <option>1</option>
<option>1</option>
        </select>

    $('#js-select2').select2({
      placeholder: "Select your option",
      allowClear: true
    });

I am using this to create a dropdown with my options, the options appear correctly however the select allows the user to type and searches. I want it to be a simple button with an arrow aligned to the right that on clicked displays all my options. How can i do this?

I’ve tried playing with the styling and using select2-dropdown however it doesn’t seem to do anything. This seems like a simple fix but I am apparently having brain block

2

Answers


  1. Try this instead:-

    <script>
    // In your Javascript (external .js resource or <script> tag)
    $(document).ready(function() {
        var $select2 = $('.js-select2');
    
        $select2.select2({
            placeholder: "Select your option",
            allowClear: true,
        });
    
        // Add a class to the select2-container when opening
        var $searchField = $('.select2-search__field');
        
        $select2.on('select2:open', function (e) {
            $searchField.prop('readonly', true);
        });
    
        // Block the Backspace key in the search box
        $searchField.on('keydown', function (e) {
            if ($searchField.prop('readonly') && e.key === 'Backspace') {
                e.preventDefault();
                return false; // To prevent further processing of the event
            }
        });
    
    });
    </script>
    

    Please try this and update here.

    Login or Signup to reply.
  2. For single select use minimumResultsForSearch = -1.

    For multiple select set disabled on search field (as stated in documentation):

    For multi-select boxes, there is no distinct search control. So, to disable search for multi-select boxes, you will need to set the disabled property to true whenever the dropdown is opened or closed

    $('#js-select2')
      .select2({
        placeholder: "Select your option",
        allowClear: true
      })
      .on('select2:opening select2:closing', function(event) {
        var $searchfield = $(this).parent().find('.select2-search__field');
        $searchfield.prop('disabled', true);
      });
    select {
      width: 100%;
    }
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
    
    
    <select id="js-select2" multiple="multiple">
      <option>1</option>
      <option>1</option>
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search