Home > database >  Continue the event after preventDefault() JS
Continue the event after preventDefault() JS

Time:02-22

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" ></span>
      <input type=file name=file>
      <input id="uploadButton"  type=submit  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)

CodePudding user response:

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;
}
  • Related