简体   繁体   中英

Will the following code reset and refresh a form after a submit?

Should the following code work to reset AND refresh a form after it has been submitted? I have a reset button on the form also that works fine if incorrect information is entered, however I would also like to reset and clear the form as well after the form has been submitted. I am still seeing the information on the form after the submit using this code.

onsubmit="setTimeout(function () { window.location.reload(); }, 10)"

Here is my current HTML:

<form action="celebrantdata.php" method="post" id="weddata">
    <div class="c1">
        <input name="Submit" type="submit" class="style2"    value="Submit" onsubmit="setTimeout(function () { window.location.reload(); }, 10)" />
        <input name="Reset" type="reset" class="style2" value="Reset" onclick="clearform();"/>
    </div>
</form>

Edit: had forgotten about the formObject.reset() function

var form = document.querySelector('#weddata');
form.addEventListener('submit', function() {
    form.reset();
}

Note that if you plan on supporting older versions of IE, you would have to use the following:

var form = document.getElementById('weddata');
if (form.addEventListener)
    form.addEventListener('submit', callback, false); // modern browsers
else if (form.attachEvent)
    form.attachEvent('onsubmit', callback); // IE

function callback() {
    form.reset();
}

I have worked out the following script:

function clearForm() {
    var form = arguments[0];
    var inputs = form.getElementsByTagName('input');

    for(var i = 0; i < inputs.length; i++) {
        if(inputs[i].type == 'text') {
            inputs[i].value = '';
        }
    }
}

With the following addition in the form tag:

onsubmit="clearForm(this);"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM