Focusing Input after Select2 close event fire
Asked Answered
E

3

3

I read always trigger "change"-event for <select>, even if the select2-option clicked is already selected and as the problem was so close to my issue I asked my question there but no answer provided. My problem is that I have a select-box constructed by Select2 and a text input. What I want to achieve is after Select2 closed (no matter the value is changed or not) my text input become focus.

So I did something logically fine as follow:

$('#select').select2({placeholder: 'City'});
$('#select')
.on('select2-close', function (e) {
   $('#hey').focus();
});

http://jsfiddle.net/sobhanattar/x49F2/8/

As you can see, the text input doesn't accept focus. After some digging in Select2 document and inspecting Events part of documentation, I realized that after Close event, there is a Focus event fire automatically. It means that after you close a Select2 select-Box, it focuses itself. So I changed my code to something like this:

$('#select').select2({placeholder: 'City'});
$('#select')
.on('select2-close', function (e) {
       $('#select').blur();
})
.on('select2-blur', function(e) {
      $('#hey').focus();
});

And it works just fine. Now I want to know that my understanding from Select2 order of events was correct or I missed something in the middle.

Endoenzyme answered 24/6, 2014 at 4:57 Comment(0)
S
6

take a look here, this question is already has an answer: Blur select2 input after close

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

elementid is the id element you want to be focused after select2 closese. i have just added $("#elementid").focus(); to the answer at link.

Sprout answered 30/6, 2015 at 21:55 Comment(1)
In the newer versions of Select2 the event name is now select2:close (colon instead of dash).Peaked
P
5

Try this one as it works:

$('#select2').on('select2:close', function (e)
{
   // your focus code for element
});
Puppetry answered 17/8, 2018 at 9:33 Comment(0)
H
0

use css:

html, body {
    height:100%
}
Honewort answered 16/9, 2017 at 8:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.