For those wanting a separate JS file to better manage the JS, you can create a library and attach an event.
Add the library to your my_module.libraries.yml file.
my_module.disable_on_click:
version: VERSION
dependencies:
- core/drupal.form
- core/jquery
js:
js/my_module_disable_on_click.js: { }
Attach the library to your form.
$form['#attached']['library'][] = 'my_module/my_module.disable_on_click';
Also add a class to your submit button. (You may wish to append or replace class, whatever you'd prefer).
$form['actions']['submit'] = [
'#attributes' => [
'class' => ['disable-on-click'],
],
];
Now you're free to edit js/my_module_disable_on_click.js how you want. This is mine that disables submit, adds the ajax loading gif and submits the form.
(function ($) {
'use strict';
Drupal.behaviors.disableOnClick = {
attach: function (context, settings) {
$('.disable-on-click').on('click', function(event) {
$(event.target).prop('disabled', true);
let button_text = $(event.target).text();
$(event.target).html(button_text + ' <img src="/core/misc/throbber-active.gif">');
$(event.target).parents('form').submit();
});
}
};
}(jQuery));