I have a form and I want to trigger an alert (using sweetalert) on submit:
<form id="verbale" class="verbale" action="editor_conferma.php" method="post">
...
<input id="go" type="submit" name="go" value="go" class="swa-confirm">
</form>
<script>
$(document).on("submit", ".swa-confirm", function (e) {
e.preventDefault();
var $myForm = $('.verbale');
if (!$myForm[0].checkValidity()) {
$myForm[0].reportValidity()
} else {
swal({
title: "Are you sure?",
text: "Did you check?",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, Submit!",
}).then(function (result) {
$myForm.submit();
});
}
});
</script>
The sweetalert dialog appears but when I confirm, the form is not passed on and submit does not seem to work.
Any hints?
Initially you gave the submit button the ID/Name of submit
- that will block the submission
You need to assign the submit to the FORM and NOT use the jQuery submit since it triggers the sweetalert again
sweetalert.js.org, has buttons
Lastly I test that Yes, Submit is clicked
Note: If you use required
, there is no need to test the validity unless you have turned standard validation off and you want to handle the validation yourself
$("#verbale").on("submit", function(e) { // or if inserted $(document).on("submit","#verbale",function() {
e.preventDefault();
const myForm = this;
if (!myForm.checkValidity()) { // this is not needed if you have required
myForm.reportValidity()
} else {
swal({
title: "Are you sure?",
text: "Did you check?",
icon: "warning",
buttons: {
cancel: true,
confirm: "Yes, Submit!"
}
}).then(function(result) {
if (result) myForm.submit(); // do not submit if cancelled
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/2.1.2/sweetalert.min.js"></script>
<form id="verbale" class="verbale" action="editor_conferma.php" method="post">
<input type="text" name="firstname" required />
<input id="go" type="submit" name="go" value="go" class="swa-confirm">
</form>
$("#verbale").on("submit", function(e) { // or if inserted $(document).on("submit","#verbale",function() {
e.preventDefault();
const myForm = this;
if (!myForm.checkValidity()) { // this is not needed if you have required
myForm.reportValidity();
} else {
Swal.fire({
title: "Are you sure?",
text: "Did you check?",
icon: "warning",
showCancelButton: true,
confirmButtonText: "Yes, Submit!",
cancelButtonText: "Cancel"
}).then((result) => {
if (result.isConfirmed) {
myForm.submit(); // submit if confirmed
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<form id="verbale" class="verbale" action="editor_conferma.php" method="post">
<input type="text" name="firstname" required />
<input id="go" type="submit" name="go" value="go" class="swa-confirm">
</form>