From 83d77cfa6226bfa3aa1ed3f5f677daad229d8518 Mon Sep 17 00:00:00 2001 From: Igor Vaynberg Date: Wed, 27 Feb 2013 08:53:17 -0800 Subject: [PATCH] fix search field focussing problems. fixes #922 --- select2.js | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/select2.js b/select2.js index 3921f2f7..f5f9084f 100644 --- a/select2.js +++ b/select2.js @@ -229,20 +229,22 @@ the specific language governing permissions and limitations under the Apache Lic $el.focus(); - /* after the focus is set move the caret to the end, necessary when we val() - just before setting focus */ - if(el.setSelectionRange) - { - el.setSelectionRange(pos, pos); - } - else if (el.createTextRange) { - range = el.createTextRange(); - range.collapse(true); - range.moveEnd('character', pos); - range.moveStart('character', pos); - range.select(); - } + /* make sure el received focus so we do not error out when trying to manipulate the caret. + sometimes modals or others listeners may steal it after its set */ + if ($el.is(":visible") && el === document.activeElement) { + /* after the focus is set move the caret to the end, necessary when we val() + just before setting focus */ + if(el.setSelectionRange) + { + el.setSelectionRange(pos, pos); + } + else if (el.createTextRange) { + range = el.createTextRange(); + range.collapse(false); + range.select(); + } + } }, 0); }