I'm trying to prevent the default bahavior of reloading the page after submitting a form, to show an information and after a second or so, continue with that event(submit) that provokes the refresh.
I've done this
HTML:
<form id="uploadForm" method=post enctype=multipart/form-data onsubmit="showConfirmationModal(event)">
<span id="confirmationModal" class="confirmModal"></span>
<input type=file name=file>
<input id="uploadButton" class="primaryButton" type=submit class="primaryButton" value=Enviar>
</form>
JS:
const showConfirmationModal = (event) => {
event.preventDefault();
const confirmation = document.getElementById('confirmationModal')
confirmation.innerText = " Uploading File ... ";
confirmation.style.display = 'inline';
setTimeout(() =>{
document.getElementById("uploadForm").submit();
},1000)
}
But the document that it's being loaded is not being sended.
Any idea?
Thank you!
(I have been looking for some info but most of people uses JQuery to solve the problem and i'ts something that I don't want to do, I'd like to use only JS)
Here is a sample code which show a feature of a modal show after the submit button is clicked and the form is processed only after the confirmation with the button shown on the modal
let submitBtn = document.getElementById("uploadButton");
let modal = document.getElementById("modal");
let confirmBtn = document.getElementById("confirm");
let uploadForm = document.getElementById("uploadForm");
submitBtn.addEventListener('click', event => {
event.preventDefault();
modal.style.display = "flex";
});
confirmBtn.addEventListener('click', event => {
event.preventDefault();
uploadForm.submit();
});
#modal{
position: absolute;
top: 0;
left:0;
display: none;
justify-content: center;
align-items: center;
width: 100vw;
height: 100vh;
background: rgba(0,0,0,0.6);
}
#modal .modal-content {
width: 80%;
height: 80%;
background: white;
display: flex;
justify-content: center;
align-items: center;
}
<form id="uploadForm" method="post" enctype="multipart/form-data">
<span id="confirmationModal" class="confirmModal"></span>
<input type=file name=file>
<input id="uploadButton" class="primaryButton" type=submit class="primaryButton" value=Enviar>
</form>
<div id="modal">
<div class="modal-content">
<button id="confirm">Confirm</button>
</div>
</div>
Change the
type=submit
to
type=button
In this case (as @mousetail mentioned) of course you have to move the event handler to the click event.
If you wanna stick with submit, try
return false
At the end of the handler.
function mySubmit(e) {
e.preventDefault();
try {
someBug();
} catch (e) {
throw new Error(e.message);
}
return false;
}