简体   繁体   中英

Submit form before redirecting to another page with JavaScript

I have a complex form; within it there's also an 'add more items' link that takes the user to another form-page (independent). What happens at the moment is that when they have edited the main form without saving it and they go to the independent form, when they come back to the main form page they have lost the edits.

<form id="form_1">

[...]
<a href="/add-something-else/">Add something else.</a>

<input type='submit'/>
</form>

add-something-else page:

<form id="form_2">
<input type='submit'/ onsubmit='go_back_to_form_1'>
</form>

Saving everything in sessionStorage would be overkill (I think), and scripts like FormPersistence.js mess about with other functionalities of my form (ie Django formset). I have tried to achieve what I want by attaching this function to my 'add something else' button:

$.when(document.forms["form1"].submit()).then(function(){
    window.location.pathname = '/add-something-esle/'
})

For some reasons, though, when I go back to form1 I see that the form wasn't saved. How can I achieve what I want?

Full page reloads clear all form state. You need a way to persist the state between full page reloads. You can use sessionStorage for that.

A <form> is made up of input elements, and you can persist all the <input.../> s to session/local storage and recover them all on page reloads; I remember answering a similar question before; but here is the summary from that answer:

basically you set an event listener on input elements you want (ie query selector); make sure they have id (or something similar) unique because we are going to use it as key t store the value;

here is an example:

function persist(event) {
  // `id` is used here
  sessionStorage.setItem(event.target.id, event.target.value);
}

// you may use a more specific selector;
document.querySelectorAll("form input").forEach((formInput) => {
  // `id` also used here for restoring value
  formInput.value = localStorage.getItem(formInput.id);
  formInput.addEventListener("change", persist);
});

this snippet will persist all <form> tag's input s values into session storage; you can also use more specialized selector in .querySelectorAll() to meet your need

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