Просмотр исходного кода

Support the `focus` event on the <select> element

This adds basic support for focusing the Select2 element by triggering
the `focus` event on the underlying <select> element.  This implicitly
adds support for <label> elements, which will trigger the `focus` event
on the `<select>` if it is clicked.

This also fixes the focus issue that previously existed if Select2 was
opened while in a <label>. The focus would be transferred to the search
dropdown, and then immediately pulled away to the <select> element. This
happened because the <label> element triggers the `focus` event when a
`click` event propagates its way up, and we do not stop the propagation
of the `click` event when it is triggered on the selection.

This closes https://github.com/select2/select2/issues/2311.
This closes https://github.com/select2/select2/issues/4203.
This closes https://github.com/select2/select2/pull/4235.
Kevin Brown 9 лет назад
Родитель
Сommit
31e7a1d4c5
3 измененных файлов с 16 добавлено и 0 удалено
  1. 4 0
      src/js/select2/core.js
  2. 6 0
      src/js/select2/dropdown/search.js
  3. 6 0
      src/js/select2/selection/single.js

+ 4 - 0
src/js/select2/core.js

@@ -181,6 +181,10 @@ define([
       });
     });
 
+    this.$element.on('focus.select2', function (evt) {
+      self.trigger('focus', evt);
+    });
+
     this._sync = Utils.bind(this._syncAttributes, this);
 
     if (this.$element[0].attachEvent) {

+ 6 - 0
src/js/select2/dropdown/search.js

@@ -62,6 +62,12 @@ define([
       self.$search.val('');
     });
 
+    container.on('focus', function () {
+      if (container.isOpen()) {
+        self.$search.focus();
+      }
+    });
+
     container.on('results:all', function (params) {
       if (params.query.term == null || params.query.term === '') {
         var showSearch = self.showSearch(params);

+ 6 - 0
src/js/select2/selection/single.js

@@ -54,6 +54,12 @@ define([
       // User exits the container
     });
 
+    container.on('focus', function (evt) {
+      if (!container.isOpen()) {
+        self.$selection.focus();
+      }
+    });
+
     container.on('selection:update', function (params) {
       self.update(params.data);
     });