2

const scriptURL = 'URL'
const form = document.forms['myform']

form.addEventListener('submit', e => {
  e.preventDefault()
  fetch(scriptURL, {
      method: 'POST',
      body: new FormData(form)
    })
    .then(response => console.log('Success!', response))
    .catch(error => console.error('Error!', error.message))
});
<form name="myform">
  <div class="col-md-6 col-sm-6">
    <div class="form-group">
      <label for="email" class="sr-only">Email</label>
      <input name="email" class="form-control" type="email" placeholder="Email" required>
    </div>
  </div>
  <div class="col-md-6 col-sm-6">
    <button type="submit" class="btn btn-default btn-block">Subscribe</button>
  </div>
</form>

How can I reset my form after handling form submission?

Here's what I am doing currently:

 form.addEventListener('submit', e => {
                          e.preventDefault()
                          fetch(scriptURL, { method: 'POST', body: new FormData(form)})
                          .then(response => console.log('Success!', response))
                          .catch(error => console.error('Error!', error.message))
                          })
                         $('#myform').reset(); // attempt to reset the form

I searched for similar threads and tried $('#myform').reset(); Clearly it's not working, I am new to Javascript if anyone can point me where to learn this form related topics then it will be great

EDIT: Form source

<form name="myform" id="myform">
    <div class="col-md-6 col-sm-6">
        <div class="form-group">
            <label for="email" class="sr-only">Email</label>
                <input name="email" class="form-control" type="email" placeholder="Email" required>
                </div>
    </div>
    <div class="col-md-6 col-sm-6">
        <button type="submit" class="btn btn-default btn-block">Subscribe</button>
    </div>
            </form>

I tried the following suggestions:

  $('#myform').val(''); // not responding
  $('#myform')[0].reset // not responding
  $('#myform').reset(); // not responding
  $('#myform').get(0).reset(); // not responding

  $('#myform').find("input:not([type="submit"), textarea").val(""); // resetting the whole page with performing submission task

  $('#myform')[0].reset() // not responding
  document.forms['myform'].val(""); // not responding
  document.getElementById('#myform').reset() // not responding
Harish ST
  • 1,475
  • 9
  • 23
remy boys
  • 2,928
  • 5
  • 36
  • 65

12 Answers12

6

Try this:

$('#myform').find("input:not([type="submit"), textarea").val("");

It will clear all data of your form. but if you have prefilled value, you should use this code: document.getElementById('myform').reset()

Note: Use 'myform' as your form id attribute. ex: <form name="myform" id="myform">

Delowar Hosain
  • 2,214
  • 4
  • 18
  • 35
3

You need to get actual form rather than jQuery object:

$('#myform').get(0).reset();
3

For the javascript to know what form to reset, you need to add id to the form, not just a name. Try,

<form name="myform" id="myform">
finnishNinja
  • 91
  • 1
  • 5
3

Please note that a form reset will bring it to its original state as it was rendered. If you had prepopulated fields, those fields will get that value again. Besides that, there are 2 things you need to fix:

  • $('#myform') needs an id="myform" in the HTML to get the form as jQuery object.
  • reset() only works on the HTML form object, not on a jQuery object. Either change your call to $('#myform')[0].reset() or to document.getElementById('myform').reset().
Jasha
  • 781
  • 9
  • 15
2

One way to clear your form is to set the value to "empty" like so:

$('#myForm').val('');

Then the form input has no value in it!

$('#myBtn').click(function () {
  $('#myForm').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type="text" value="hello world" id="myForm">

<button id="myBtn">myBtn</button>
JKortmann
  • 39
  • 4
2
document.getElementById('#myform').reset() // not responding

You were almost there.. getElementByID so you can omit # in ('#myform')

This would work if you used document.getElementById('myform').reset();

For some reason reset() does not work with jquery only with pure JS.

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
2

jQuery is not required for everything

<form action='server-script.cgi' onsubmit='this.submit();this.reset();return false;'>
  <blah>...</blah>
</form>
Dharman
  • 30,962
  • 25
  • 85
  • 135
atesin
  • 21
  • 1
1
  1. Get the real form $('#myForm')[0].reset()

  2. You need to add an id tag to your form <form id="myForm">

If you just used plain js, you could go with document.getElementById('myForm').reset() but still, add an id tag to your form

Edit: corrections pointed out in the comment

Isitar
  • 1,286
  • 12
  • 29
  • Even with the id your selector seems wrong to me. Also use .get(0). If you really feel the urge to use jquery atleast be consistent in it. – Lain Apr 25 '18 at 06:20
  • Could you elaborate what event you mean? – Isitar Apr 25 '18 at 06:24
  • They didn't say event ;-). Your jQuery statement is not fully correct. The `#` is missing in the selector and you should call `reset()` as a function. There's nothing wrong using `[0]` instead of `get(0)`: https://learn.jquery.com/using-jquery-core/faq/how-do-i-pull-a-native-dom-element-from-a-jquery-object/ – Jasha Apr 25 '18 at 06:28
0

document.getElementById("myform").addEventListener('submit',reset_form);

function reset_form(event) {
  //Your code goes here
  document.getElementById("myform").reset();
}
<form name="myform" id="myform">
  <div class="col-md-6 col-sm-6">
    <div class="form-group">
      <label for="email" class="sr-only">Email</label>
      <input name="email" id="myform" class="form-control" type="email" placeholder="Email" required>
    </div>
  </div>
  <div class="col-md-6 col-sm-6">
    <button type="submit" class="btn btn-default btn-block">Subscribe</button>
  </div>
</form>

Are you looking for this ? And do your coding inside the function! Alternatively, If you don't want the form to submit, you can use the button type="button" instead of "submit" also.

Harish ST
  • 1,475
  • 9
  • 23
0

Since form is declared and resused in the listener anyway, could just call a reset on it.

<html>
    <head>
        <script>
            window.onload = function(){
                const scriptURL = 'URL';
                const form = document.forms['myform'];

                form.addEventListener('submit', e => {
                    e.preventDefault()

                    fetch(scriptURL, {
                        method: 'POST',
                        body: new FormData(form)
                    })
                    .then(response => console.log('Success!', response))
                    .catch(error => console.error('Error!', error.message));

                    form.reset() //Reset the form
                })
            }
        </script>
    </head>

    <body>
        <form name="myform">
            <div class="col-md-6 col-sm-6">
                <div class="form-group">
                    <label for="email" class="sr-only">Email</label>
                    <input name="email" class="form-control" type="email" placeholder="Email" required>
                </div>
            </div>
            <div class="col-md-6 col-sm-6">
                <button type="submit" class="btn btn-default btn-block">Subscribe</button>
            </div>
        </form>
    </body>
</html>
Lain
  • 3,657
  • 1
  • 20
  • 27
0

try this:

$('#yourInputID').val('');

this will reset reset the selected input by its Id.

Yehia Fouad
  • 21
  • 1
  • 3
0

Reason

while using fetch() for the data is already delivered and you only get response object back from server. the reset() inside fetch.then() won't execute.

Workaround

one of the way to make things work is , instead of getting form data inside fetch , you should collect data before that & saved it somewhere and reset the form.

Code

form.addEventListener('submit', e => {
  e.preventDefault()

  const options = {
     method: 'POST',
     body: new FormData(form),
  }

  form.reset();

  fetch(scriptURL, options)
    .then(response => console.log('Success!', response))
    .catch(error => console.error('Error!', error.message))
  });
Muhammad Uzair
  • 394
  • 5
  • 9