htools-8.x-1.x-dev/modules/htools_entity_views_filter/js/autosubmit.js
modules/htools_entity_views_filter/js/autosubmit.js
/**
* @file auto_submit.js
*
* Provides a "form auto-submit" feature for the Better Exposed Filters module.
*/
(function ($, Drupal, once) {
/**
* To make a form auto submit, all you have to do is 3 things:
*
* Use the "htools_entity_views_filter/autosubmit" js library.
*
* On gadgets you want to auto-submit when changed, add the
* data-evf-auto-submit attribute. With FAPI, add:
* @code
* '#attributes' => array('data-evf-auto-submit' => ''),
* @endcode
*
* If you want to have auto-submit for every form element, add the
* data-evf-auto-submit-full-form to the form. With FAPI, add:
* @code
* '#attributes' => array('data-evf-auto-submit-full-form' => ''),
* @endcode
*
* If you want to exclude a field from the evf-auto-submit-full-form auto
* submission, add an attribute of data-evf-auto-submit-exclude to the form
* element. With FAPI, add:
* @code
* '#attributes' => array('data-evf-auto-submit-exclude' => ''),
* @endcode
*
* Finally, you have to identify which button you want clicked for autosubmit.
* The behavior of this button will be honored if it's ajaxy or not:
* @code
* '#attributes' => array('data-evf-auto-submit-click' => ''),
* @endcode
*
* Currently only 'select', 'radio', 'checkbox' and 'textfield' types are
* supported. We probably could use additional support for HTML5 input types.
*/
Drupal.behaviors.entityViewsFilterAutoSubmit = {
attach: function(context) {
// e.keyCode: key
var ignoredKeyCodes = [
16, // shift
17, // ctrl
18, // alt
20, // caps lock
33, // page up
34, // page down
35, // end
36, // home
37, // left arrow
38, // up arrow
39, // right arrow
40, // down arrow
9, // tab
13, // enter
27 // esc
];
// When exposed as a block, the form #attributes are moved from the form
// to the block element, thus the second selector.
// @see \Drupal\block\BlockViewBuilder::preRender
var selectors = 'form[data-evf-auto-submit-full-form], [data-evf-auto-submit-full-form] form, [data-evf-auto-submit]';
function triggerSubmit ($target) {
$target.closest('form').submit();
}
// The change event bubbles so we only need to bind it to the outer form
// in case of a full form, or a single element when specified explicitly.
once('evf-auto-submit', selectors).forEach(selector => {
$(selector).on('change keyup keypress', function (e) {
var $target = $(e.target);
// Don't submit on changes to excluded elements or a submit element.
if ($target.is('[data-evf-auto-submit-exclude], :submit')) {
return true;
}
// Use debounce to prevent excessive submits on text field changes.
// Navigation key presses are ignored.
else if ($target.is(':text:not(.hasDatepicker), textarea') && $.inArray(e.keyCode, ignoredKeyCodes) === -1) {
Drupal.debounce(triggerSubmit, 500)($target);
}
// Only trigger submit if a change was the trigger (no keyup).
else if (e.type === 'change') {
triggerSubmit($target);
}
});
})
},
};
}(jQuery, Drupal, once));
