[Drupal8] Prevent double click

// prevent-double-click.js
// place the file in ./modules/custom/mymodule/js/
(function ($, Drupal) {
  Drupal.behaviors_mymodule_prevent_double_click = {
    attach: function attach(context, settings) {
      // Prevent double click on the button
      $('form').submit(function () {
        console.log($(this).find('.form-submit').val() + ' clicked');
        $(this).find('.form-submit').prop('disabled', true);
        return true;
      });
    }
  };
})(jQuery, Drupal);
// mymodule.libraries.yml
// place the file in ./modules/custom/mymodule/
prevent-double-click:
  js:
    js/prevent-double-click.js: {}
  dependencies:
    - core/drupal
    - core/jquery
    - core/once

Example usage in form:
$form['#attached']['library'][] = 'mymodule/prevent-double-click';

Categories: