Just some notes on triggering an AJAX Form submit programmatically in Drupal 8+:
- AJAX properties can be found here, but the list was not complete. Especially useful is to know about ''disable-refocus' => TRUE' property, to prevent from refocussing on the submit button after AJAX submit. I added it to the list in the documentation
- Default event for submit, button and image_button is "mousedown" (not "click")! So I also added that information to the API Docs. This is important to know, as triggering a "click" event just won't work! I'm wondering why "mousedown" was chosen and not "mouseup", but that's a different topic.
So here's the snippet I used in Homebox 3.0.x development to implement auto-submit for the AJAX portlet forms:
/**
* Implements autosubmit on value change for the portlet forms
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attach homebox drag drop behaviors.
*/
behaviors.homeboxPortletAutoSubmit = {
attach(context) {
once("porletautosubmit", "input, select, textarea", context).forEach(
(input) => {
input.addEventListener(
"change",
Drupal.debounce(function () {
const form = this.closest("form");
const submitButton = form.querySelector('input[type="submit"]');
if (submitButton) {
// Drupal AJAX form submits are triggered on mousedown!
// @ee https://www.drupal.org/project/drupal/issues/634616
// @see https://www.drupal.org/files/issues/interdiff-634616-94-99.txt
// @todo replace jquery code with vanilla code:
$(submitButton).trigger("mousedown");
} else {
form.submit();
}
}, 500),
);
},
);
},
};