PageSourceSearch

https://www.vttresearch.com/modules/contrib/better_exposed_filters/js/auto_submit.js?tltduu

js vttresearch.com collected 2026-09-24 08:40:36 UTC 7,971 bytes, 206 lines download raw bytes

1/**
2 * @file
3 * auto_submit.js
4 *
5 * Provides a "form auto-submit" feature for the Better Exposed Filters module.
6 */
7
8(function ($, Drupal, once) {
9
10  /**
11   * To make a form auto submit, all you have to do is 3 things:.
12   *
13   * Use the "better_exposed_filters/auto_submit" js library.
14   *
15   * On gadgets, you want to auto-submit when changed, add the
16   * data-bef-auto-submit attribute. With FAPI, add:
17   * @code
18   *  '#attributes' => array('data-bef-auto-submit' => ''),
19   * @endcode
20   *
21   * If you want to have auto-submit for every form element, add the
22   * data-bef-auto-submit-full-form to the form. With FAPI, add:
23   * @code
24   *   '#attributes' => array('data-bef-auto-submit-full-form' => ''),
25   * @endcode
26   *
27   * If you want to exclude a field from the bef-auto-submit-full-form auto
28   * submission, add an attribute of data-bef-auto-submit-exclude to the form
29   * element. With FAPI, add:
30   * @code
31   *   '#attributes' => array('data-bef-auto-submit-exclude' => ''),
32   * @endcode
33   *
34   * Finally, you have to identify which button you want clicked for autosubmit.
35   * The behavior of this button will be honored if it's ajax or not:
36   * @code
37   *  '#attributes' => array('data-bef-auto-submit-click' => ''),
38   * @endcode
39   *
40   * Currently only 'select', 'radio', 'checkbox' and 'textfield' types are
41   * supported. We probably could use additional support for HTML5 input types.
42   */
43  Drupal.behaviors.betterExposedFiltersAutoSubmit = {
44    attach: function (context, settings) {
45
46      let selectors = '';
47      if (drupalSettings.better_exposed_filters.auto_submit_sort_only
47) {
48        selectors = 'form[data-bef-auto-submit-sort-only] .form-item-sort-order';
49      }
50      else {
51        // When exposed as a block, the form #attributes are moved from the form
52        // to the block element, thus the second selector.
53        // @see \Drupal\block\BlockViewBuilder::preRender
54        selectors = 'form[data-bef-auto-submit-full-form], [data-bef-auto-submit-full-form] form, [data-bef-auto-submit]';
55      }
56
57      $(selectors, context).addBack(selectors).find('input:text:not(.hasDatepicker), textarea, select').each(function () {
58        const $el = $(this);
59        const $valueLength = $el.val().length * 2;
60        const $tagName = $el[0].tagName;
61        if ($tagName === 'SELECT') {
62          setFocus($el);
63        }
64        else {
65          $el[0].setSelectionRange($valueLength, $valueLength);
66          setFocus($el, $valueLength);
67        }
68      });
69
70      function setFocus($el) {
71        const observer = new IntersectionObserver((entries) => {
72
73          entries.forEach(entry => {
74            if (entry.isIntersecting) {
75              const $lastTriggeredSelector = $(settings.bef_autosubmit_target).attr('data-drupal-selector');
76              if ($el.attr('data-drupal-selector') && $el.attr('data-drupal-selector') === $lastTriggeredSelector) {
77                $el.focus();
78              }
79            }
80          });
81        });
82
83        observer.observe($el.get(0));
84      }
85
86      // The change event bubbles, so we only need to bind it to the outer form
87      // in case of a full form, or a single element when specified explicitly.
88      $(selectors, context).addBack(selectors).each(function (i, e) {
89        const $e = $(e);
90        // Store the current form.
91        let $needsAutoSubmit = $e;
92
93        // Retrieve the autosubmit delay for this particular form.
94        let autoSubmitDelay = 500;
95        if (e.hasAttribute('data-bef-auto-submit-delay')) {
96          autoSubmitDelay = $e.data('bef-auto-submit-delay');
97        }
98        else if (!e.hasAttribute('data-bef-auto-submit-full-form')) {
99          // Find the container but skip checking if this element already is
100          // 'form[data-bef-auto-submit-full-form]'.
101          const $container = $e.closest('[data-bef-auto-submit-full-form]');
102          if ($container.length && $container.get(0).hasAttribute('data-bef-auto-submit-delay')) {
103            $needsAutoSubmit = $container;
104            autoSubmitDelay = $container.data('bef-auto-submit-delay');
105          }
106        }
107
108        // Ensure that have a delay.
109        autoSubmitDelay = autoSubmitDelay || 500;
110        // Separate debounce instance for date inputs change event.
111        let dateInputChangeDebounce = Drupal.debounce(triggerSubmit, autoSubmitDelay, false);
112
113        // Attach event listeners.
114        $(once('bef-auto-submit', $needsAutoSubmit))
115          // On change, trigger the submit immediately unless it's a date
116          // input which emits change event as soon as the date value is
117          // valid, even if user is still typing.
118          .on('change', function (e) {
119            return e.target.type === 'date'
120              ? dateInputChangeDebounce(e)
121              : triggerSubmit(e);
122          })
123          // On keyup, wait for a specified number of milliseconds before
124          // triggering autosubmit. Each new keyup event resets the timer.
125          .on('keyup', Drupal.debounce(triggerSubmit, autoSubmitDelay, false));
126      });
127
128      /**
129       * Triggers form autosubmit when conditions are right.
130       *
131       * - Checks first that the element that was the target of the triggering
132       *   event is `:text` or `textarea`, but is not `.hasDatePicker`.
133       * - Checks that the keycode of the keyup was not in the list of ignored
134       *   keys (navigation keys etc.).
135       *
136       * @param {object} e - The triggering event.
137       */
138      function triggerSubmit(e) {
139        // e.keyCode: key.
140        const ignoredKeyCodes = [
141          16, // Shift.
142          17, // Ctrl.
143          18, // Alt.
144          20, // Caps lock.
145          33, // Page up.
146          34, // Page down.
147          35, // End.
148          36, // Home.
149          37, // Left arrow.
150          38, // Up arrow.
151          39, // Right arrow.
152          40, // Down arrow.
153          9, // Tab.
154          13, // Enter.
155          27,  // Esc.
156          32, // Space.
157        ];
158
159        // Triggering element.
160        const $target = $(e.target);
161        const $form = e.target.form ? $(e.target.form) : $target.closest('form');
162        const $submit = $form.find('[data-bef-auto-submit-click]');
163        const mediaQuery = $target.closest('form').data('bef-auto-submit-media-query');
164
165        // Don't submit when the document doesn't match the media query string.
166        if (mediaQuery && !matchMedia(mediaQuery).matches) {
167          return true;
168        }
169
170        // Don't submit on changes to excluded elements,submit elements, or select2 autocomplete.
171        if ($target.is('[data-bef-auto-submit-exclude], :submit, .select2-search__field, .chosen-search-input')) {
172          return true;
173        }
174
175        // Submit only if this is a non-datepicker textfield and if the
176        // incoming keycode is not one of the excluded values, and it has a
177        // minimum character length.
178        let textfieldMinimumLength = $target.closest('form').data('bef-auto-submit-minimum-length') || 1;
179        let inputTextLength = $target.val().length;
180        let textfieldHasMinimumLength = ($target.is(':text:not(.hasDatepicker), textarea') && inputTextLength >= textfieldMinimumLength) || $target.is('[type="checkbox"], [type="radio"]');
181        if (
182          (textfieldHasMinimumLength || inputTextLength === 0)
183          && $.inArray(e.keyCode, ignoredKeyCodes) === -1
184          && !e.altKey
185          && !e.ctrlKey
186          && !e.shiftKey
187        ) {
188          $submit.click();
189        }
190        // Only trigger submit if a change was the trigger (no keyup).
191        else if (e.type === 'change') {
192          let target = $target.is(':text:not(.hasDatepicker), textarea');
193          if (target && textfieldHasMinimumLength) {
194            $submit.click();
195          }
196          else if (!target) {
197            $submit.click();
198          }
199        }
200
201        settings.bef_autosubmit_target = $target;
202      }
203    },
204  };
205
206}(jQuery, Drupal, once));

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.