Blur Select2 input after close
Asked Answered
S

1

5

I want the select2 element to lose the focus when the select2-close event is triggered, what I have tried so far was:

.on("select2-close", function (e) {
    var $focused = $(':focus');
    $focused.blur();
});

and some variations to get focused element like document.activeElement, $(e.target) non f these worked.

JSFiddle

Somniloquy answered 16/1, 2014 at 8:53 Comment(1)
please view my comment at link https://mcmap.net/q/2030846/-focusing-input-after-select2-close-event-fireRedwine
S
10

You need to remove the .select2-container-active class from the containing divider:

.on("select2-close", function () {
    setTimeout(function() {
        $('.select2-container-active').removeClass('select2-container-active');
        $(':focus').blur();
    }, 1);
});

I've used a setTimeout here as a hacky way to ensure that this triggers after the plugin itself finalises the close.

JSFiddle demo.

Subnormal answered 16/1, 2014 at 8:56 Comment(6)
Are you sure that your code removed the focus from the select2 element? Just try to log the focused element after your call. Really simple test.Somniloquy
@akoskm ah sorry, I'd removed your part of the code. I've added $(':focus').blur(); back in and updated the JSFiddle.Subnormal
Okay, I realized that your fiddle is different from your answer and without setTimeout it won't work. Please edit your answer and I'll accept it. The 'setTimeout' is crucial in this case.Somniloquy
@akoskm ah sorry, I'd forgotten about that too! Slow morning...!Subnormal
This select2 Github issue may be related - "Blur event fires at the wrong time with newer versions of jQuery"Mufinella
whats the containing divider?Package

© 2022 - 2024 — McMap. All rights reserved.