简体   繁体   中英

HTML form reset after AJAX submit

I have a simple HTML form, with reset and submit buttons, which is submitted using an AJAX call.

Before any submit, the reset button is restoring form's initial state and I'm OK with that!

Buf after submitting the form, if I modify input values, I would like the reset button to restore form's state as it was after the last successful submission!

Is there any way to do this without reloading or recreating the form?

Best regards,

Thierry

It depends how you are submitting the form, but in general, with ajax, there is no kind of redirect, so the only question is removing the currently entered data to its default value.

Simple, at the start of the form loading (possibly at page load, but if its being generated after somehow, then right after its made), simply loop through the elements of the form and keep track of the values and store it to some kind of dictionary or array, then, after the ajax is submitted, reloop through the form and reset the values to the other corresponding values from before.

For example, if I had a form with an ID of "testForm"

let list = Array.apply(0, testForm.elements).map(x=>({name:x.name, value:x.value}))

...do ajax stuff, then after submitting the form:

Array.apply(0, testForm.elements).forEach((x, i) => {
    x.name = list[i].name;
    x.value = list[i].value
});

should reset it to the default values.. Possibly resetting the name is unnecessary, but its possible it was changed theoretically..

The main idea - save state

 const input = document.getElementById("name"); const reset = document.getElementById("btn-reset"); const save = document.getElementById("btn-save"); const state = { name: '' }; save.addEventListener('click', () => { // send AJAX const value = input.value; setTimeout(() => { const serverResponse = {name: value}; state.name = serverResponse.name; }, 1000) }); reset.addEventListener('click', () => { input.value = state.name });
 <input id="name" value=""> <button id="btn-reset">Reset</button> <button id="btn-save">Save</button>

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