41

I've tried it a few different ways based on searches I've done on the subject and for some reason I can't get it to work. I just want my text inputs and textarea to clear after I hit the submit button.

Here's the code.

<div id="sidebar-info">
    <form name="contact-form" action="formprocess.php" method="post" target="ninja-frame">
        <h1>By Phone</h1>
        <p id="by-phone">XXX-XXX-XXXX</p>
        <h1>By Email</h1>
        <p id="form-row">Name</p>
        <input name="name" id="name" type="text" class="user-input" value="">
        <p id="form-row">Email</p>
        <input name="email" id="email" type="text" class="user-input" value="">
        <p id="form-row">Message</p>
        <textarea name="message" id="message" class="user-input" rows="10" maxlength="1500"></textarea>
        <p>*Please fill out every field</p>
        <input type="submit" value="Submit" id="submit" onclick="submitForm()">

        <script>
            function submitForm() {
            document.contact-form.submit();
            document.contact-form.reset();
            }
        </script>
    </form>
</div>
Szuturon
  • 931
  • 4
  • 17
  • 28
  • 3
    AFAIK, your `
    ` is being submitted. Which means that your browser will navigate to a different page and further actions in your current page won't make much sense. Or, am I missing something?
    – Alexander Jan 29 '13 at 18:01
  • 1
    @Alexander How do you know it's being fully submitted? We don't see any handlers for the `onsubmit` event, but they could easily be there. The handler could stop the submission based on whatever condition. I don't agree clearing the form would be the best idea, but it's up to the OP – Ian Jan 29 '13 at 19:21

12 Answers12

57

Your form is being submitted already as your button is type submit. Which in most browsers would result in a form submission and loading of the server response rather than executing javascript on the page.

Change the type of the submit button to a button. Also, as this button is given the id submit, it will cause a conflict with Javascript's submit function. Change the id of this button. Try something like

<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">

Another issue in this instance is that the name of the form contains a - dash. However, Javascript translates - as a minus.

You will need to either use array based notation or use document.getElementById() / document.getElementsByName(). The getElementById() function returns the element instance directly as Id is unique (but it requires an Id to be set). The getElementsByName() returns an array of values that have the same name. In this instance as we have not set an id, we can use the getElementsByName with index 0.

Try the following

function submitForm() {
   // Get the first form with the name
   // Usually the form name is not repeated
   // but duplicate names are possible in HTML
   // Therefore to work around the issue, enforce the correct index
   var frm = document.getElementsByName('contact-form')[0];
   frm.submit(); // Submit the form
   frm.reset();  // Reset all form data
   return false; // Prevent page refresh
}
Kami
  • 19,134
  • 4
  • 51
  • 63
14

since you are using jquery library, i would advise you utilize the reset() method.

Firstly, add an id attribute to the form tag

<form id='myForm'>

Then on completion, clear your input fields as:

$('#myForm')[0].reset();
Rotimi
  • 4,783
  • 4
  • 18
  • 27
8

You can use HTMLFormElement.prototype.reset according to MDN

document.getElementById("myForm").reset();
Jack G
  • 4,553
  • 2
  • 41
  • 50
  • In addition to mentioning the reference of your answer, it is more appropriate to include part of your answer. This could be useful for future readers in case the reference is no longer available. – dm_tr Dec 21 '20 at 23:40
  • I added the code snippet and linked to MDN. Never link to W3Schools and certainly never use it as a reference. It's a non-authoritative and sometime poor quality resource and isn't endorsed by or affiliated with W3C. Always use MDN – Jack G Dec 21 '20 at 23:45
4

You can try this:

function submitForm() {
  $('form[name="contact-form"]').submit();
  $('input[type="text"], textarea').val('');
}

This script needs jquery to be added on the page.

Jai
  • 74,255
  • 12
  • 74
  • 103
  • 1
    jquery is good to have anyways.... Also @Jai would this not clear all input elements, and not bind only to the those in the current form? – Nick Mitchinson Jan 29 '13 at 18:02
4

You can assign to the onsubmit property:

document.querySelector('form').onsubmit = e => {
   e.target.submit();
   e.target.reset();
   return false;
};

https://developer.mozilla.org/docs/Web/API/GlobalEventHandlers/onsubmit

Zombo
  • 1
  • 62
  • 391
  • 407
3

The easiest way would be to set the value of the form element. If you're using jQuery (which I would highly recommend) you can do this easily with

$('#element-id').val('')

For all input elements in the form this may work (i've never tried it)

$('#form-id').children('input').val('')

Note that .children will only find input elements one level down. If you need to find grandchildren or such .find() should work.

There may be a better way however this should work for you.

Nick Mitchinson
  • 5,452
  • 1
  • 25
  • 31
2
$('#contact-form input[type="text"]').val('');
$('#contact-form textarea').val('');
Nimantha
  • 6,405
  • 6
  • 28
  • 69
1

I used the following with jQuery:

$("#submitForm").val("");

where submitForm is the id for the input element in the html. I ran it AFTER my function to extract the value from the input field. That extractValue function below:

function extractValue() {
    var value = $("#submitForm").val().trim();
    console.log(value);
};

Also don't forget to include preventDefault(); method to stop the submit type form from refreshing your page!

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Ado Moshe
  • 209
  • 2
  • 6
1

Just include this line at the end of function:

document.getElementById("btnsubmit").value = "";
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Omkar Bhad
  • 19
  • 1
1
var btnClear = document.querySelector('button');
var inputs = document.querySelectorAll('input');
 
btnClear.addEventListener('click', () => {
    inputs.forEach(input =>  input.value = '');
});
  • While this code may resolve the OP's issue, it is best to include an explanation as to how your code addresses the OP's issue. In this way, future visitors can learn from your post, and apply it to their own code. SO is not a coding service, but a resource for knowledge. Also, high quality, complete answers are more likely to be upvoted. These features, along with the requirement that all posts are self-contained, are some of the strengths of SO as a platform, that differentiates it from forums. You can edit to add additional info &/or to supplement your explanations with source documentation. – ysf Jun 23 '20 at 16:56
1

btnSave.addEventListener("click", () => {
  inputs.forEach((input) => (input.value = ""));
});

**Use the button you want to clear the inputs after clicking on it instead of the btnSave **

0

On the function, you are running upon the event of the submit button. If you are using the form itself to run any if statements then do the following inside the function for the event.

//assigned form id value to a variable. 
let myFormId = $('form').attr('id');
//if statement or loop goes here.
document.getElementById(myFormId).reset();