Currently having some issues with jQuery Form Submissions in my project.
My project contains a general jQuery Code which prevents form double submissions (e.g. someone clicks the 'submit' button multiple times).
//prevent multiple form submissions
jQuery.fn.preventDoubleSubmission = function () {
$(document).on('submit', this, function (e) {
let $form = $(this);
if ($form.data('submitted') === true) {
e.preventDefault();
} else {
$form.data('submitted', true);
}
});
return this;
};
$(function () {
$('form').preventDoubleSubmission();
});
This code is included into every single page - so every form should be 'protected'.
For some specific forms I need to check some values before they are submitted - and show a confirm box, if some values are missing (e.g. Are you sure you want to submit this form without value X?)
Here's the code:
$(document).on('submit', 'form[name="article"]', function (e) {
e.preventDefault();
let form = this;
let $form = $(form);
let $category = $form.find('select#article_category'); //get category
if ($category.length && !$category.val()) { //check if category is selected
$.confirm({ //jquery confirm plugin
title: "Are you sure?",
content: "Value X is missing - continue?",
buttons: {
confirm: {
action: function () {
$form.off('submit');
form.submit();
}
}
}
});
} else {
$form.off('submit');
form.submit();
}
});
So basically, if the user tries to submit the form, but the value X is missing, there will be a Yes/No Popup first - if the value exists, the form will be submitted right away.
Problem:
When I want to submit the form, I call $form.off('submit');
to remove the event handler and submit afterwards with form.submit();
. Sadly this also removes my preventDoubleSubmission event handler, which allows double submissions again.
Is there a way to fix my issue? Thanks