skip to Main Content

I have a simple form being submitted into a third-party form/db location (Acoustic) and I’m trying to prevent the page from being redirected after submission.

    <form method="post" action="my-form-url-goes-in-here">
      // form labels and fields
    </form>
    <button type="submit" id="mybtn">Submit</button>

I’ve tried using preventDefault() and return false as options to override that behavior but for some reason they don’t work.

    document.querySelector("#mybtn").addEventListener("click", function () {
      document.querySelector("form").submit(function (e) {
        e.preventDefault();

        return false;
      });
    });

What are some options for achieving this behavior.

2

Answers


  1. Ideally, you are meant to use your submit button within the form element, then you can target the form

    <form method="post" id="my-form">
          // form labels and fields
     <button type="submit">Submit</button>
        </form>
       
    $(document).on('submit', '#my-form', function(e){
        e.preventDefault();
     
       
      });
    

    the document has access to the elements in the dom, you can target specific element using their id, and thats what i have done here, the call back function has reference to the form

    Login or Signup to reply.
  2. You should just listen for the submit event. There is no need for listening for the click event first.

    document.querySelector("form").addEventListener('submit', e => {
      e.preventDefault();
      console.log('submitting...');
    });
    <form name="form01" method="post" action="my-form-url-goes-in-here">
      <input name="test">
      <button type="submit">Submit</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search