I am using Nette, Contributte Live-form-validation to validate my forms and Naja in web apps. I would like to prevent double submit form my ajax and non-ajax forms.
After some research I create an own solution.
For non-ajax part you need to disable input in form submit event when submit is not prevented by form-validation.
// $root is scope where to find input submits
notAjaxInit($root: JQuery): void {
$root.find('input[type="submit"]:not(.ajax)')
.each((i, input) => {
const $input = $(input);
const form = <HTMLFormElement>$input.closest('form').get(0);
// on form submit
form?.addEventListener('submit', e => {
// check if validation does not prevent submittion
if (e.defaultPrevented === false) {
// disable by class, not by property (corrupt form data)
input.classList.add('disabled');
}
})
})
}
For ajax forms, which are handled by Naja you can achieve this by extension.
naja.addEventListener('before', event=> {
if (event.currentTarget) {
const $el = $(event.currentTarget);
if ($el.is('input[type="submit"]')) {
$el.prop('disabled', 1);
}
}
});
naja.addEventListener('complete', event => {
if (event.currentTarget) {
const $el = $(event.currentTarget);
if ($el.is('input[type="submit"]')) {
$el.prop('disabled');
}
}
})
Bonus tip: you can init non-ajax part also with naja like this:
// document ready
naja.addEventListener('init', () => this.notAjaxInit($('body')));
// snippet update
naja.snippetHandler.addEventListener('afterUpdate', (e) => this.notAjaxInit($(<HTMLElement>e.detail.snippet)));