javascriptjquery-select2

Disable auto focus on drop-down open of select2?


I tried to disable auto focus of input search inside select2 especially on mobile to disable keyboard popup. However, as documented here:

select2 will not be triggering the native events. select2 will also not be triggering non-native versions of the events, which is less of an issue as we still have the option to add the native events without breaking compatibility.

So the only way I could do is to try to get every input box inside select2 that was currently on focused and set lose focus, but has no luck.

$("select").select2().on("select2-open",":input",function(){
    setTimeout(function(){
        $(":focus").blur();
    }, 50);
});

Is there any possibility that I could achieve that result above? Thanks.


Solution

  • Finally, I managed to find solution which works just fine for me as below:

    /* Hide keyboard on select2 open event */
    function hideSelect2Keyboard(e){
        $('.select2-search input, :focus,input').prop('focus',false).blur();
    }
    
    $("select").select2().on("select2-open", hideSelect2Keyboard);
    
    $("select").select2().on("select2-close",function(){
        setTimeout(hideSelect2Keyboard, 50);
    });
    

    Tested on Tablet, and iOS device. In function hideSelect2Keyboard(), I searched for every current focus element, include input field which could be used to initialized select2, setting .prop('focus',false) which will remove focus and consequently disable keyboard popup on select2-open and select2-close event, by chaining .blur() is to remove focus border from element. Then I attached this function to select event open and close and it works just fine.

    I hope this will help other who searching for this as me too. Thanks.