Prevent select2 from autmatically focussing its search-input when dropdown is opened

后端 未结 10 444
野性不改
野性不改 2021-01-11 16:02

I\'m looking for a way to prevent select2\'s search-input being automatically focussed when the select2-dropdown is opened. I know this is select2\'s intended default behavi

10条回答
  •  心在旅途
    2021-01-11 16:28

    I got JQuery's "too much recursion" error in the console when using Choma's solution.

    The following worked for me for v4:

    // keep search input available, but avoid autofocus and thus mobile 
    // keyboard appearing when dropdown opens.
    $('body').on('select2:open','#subject', function (e) {
        $('#modal .select2-search input').attr('readonly',true);
        $('#modal .select2-search input').click(function(ev){
            $('#modal .select2-search input').attr('readonly',false);
        });
    });
    

    As you can tell this select2 field is on a modal with the id modal and the select2 field itself has an id of subject. Of course change the selector to what's appropriate for your own code.

    It basically adds a readonly attribute to the input when the select2 field opens preventing a mobile keyboard from appearing, and then removes it when the search field is clicked/pressed on allowing the keyboard to appear only then.

提交回复
热议问题