Focusing Input after Select2 close event fire

╄→гoц情女王★ 提交于 2019-12-19 12:23:30

问题


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.


回答1:


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.




回答2:


use css:

html, body {
    height:100%
}



回答3:


Try this one as it works:

$('#select2').on('select2:close', function (e)
{
   // your focus code for element
});


来源:https://stackoverflow.com/questions/24378615/focusing-input-after-select2-close-event-fire

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!