Clearing my form inputs after submission

前端 未结 9 936
Happy的楠姐
Happy的楠姐 2020-11-30 04:25

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

相关标签:
9条回答
  • 2020-11-30 04:53

    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
    }
    
    0 讨论(0)
  • 2020-11-30 04:53

    Try this:

    $('#contact-form input[type="text"]').val('');
    $('#contact-form textarea').val('');
    
    0 讨论(0)
  • 2020-11-30 04:53

    Just include this line at the end of function and the Problem is solved easily!

    document.getElementById("btnsubmit").value = "";
    
    0 讨论(0)
提交回复
热议问题