1

I'm trying to do this with pure javascript, not with jquery. I have a div that has an id form and contains a form inside it. How do I empty the content of this div and replace it with text form submitted, when the form is submitted?

<div class="form">
   <form action="">
    ...
   </form>
</div>
Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62

3 Answers3

0

Listen to the submit event on the form, then replace the innerHTML of the container.

document.addEventListener('DOMContentLoaded', function() {
  const formContainer = document.querySelector('.form');
  const form = formContainer.querySelector('form');
  
  form.addEventListener('submit', function () {
    formContainer.innerHTML = `Thank you for telling me about ${form.someInput.value}`;
  });
});
<div class="form">
  <form>
    <input name="someInput" type="text" />
    
    <button type="submit">submit</button>
  </form>
</div>
Austin Brunkhorst
  • 20,704
  • 6
  • 47
  • 61
0

Give an ID to the form and the div around it:

<div class="form" id="form-wrapper">
   <form id="my-form" action="#">

   </form>
</div>

and the JavaScript you asked:

var submitted = function(e){
  var d = document.getElementById("form-wrapper");
  d.innerHTML = "Form Submitted";
  e.preventDefault();
}

var ele = document.getElementById("my-form");
if(ele.addEventListener){
    ele.addEventListener("submit", submitted, false);  //Modern browsers
}else if(ele.attachEvent){
    ele.attachEvent('onsubmit', submitted);            //Old IE
}

but keep in mind here we are simply preventing the form from submitting so i'm guessing you'll want to add some AJAX processing inside the submitted function.

Julien
  • 2,217
  • 2
  • 28
  • 49
0

There's a couple of things to note here...

  1. When a form normally submits, it navigates away from the page so you'll want to prevent that.
  2. Given you've now interrupted the normal form submission process, you'll need to submit the form asynchronously and ideally wait for the request to complete
  3. In the same place, you can then update the contents of your <div>

For example, in a <script> tag at the bottom of your document, just before the </body>...

let div = document.querySelector('.form') // find the first element by class
let form = div.querySelector('form')      // find the form by tag
form.addEventListener('submit', e => {
  // stop the page navigating away
  e.preventDefault()

  // submit the form via AJAX
  fetch(form.action, {
    method: form.method
    body: new FormData(form)
  }).then(res => {
    // now update the <div> contents
    div.innerHTML = res.ok ? 'Form Submitted' : 'Form submit failed'
  })
})

Note, this will submit the form as multipart/form-data. If your backend is only expecting application/x-www-form-urlencoded, you'll need to do a bit more work. See How do I post form data with fetch api?

Phil
  • 157,677
  • 23
  • 242
  • 245