Home >Web Front-end >JS Tutorial >How Can I Preserve Form Data Across Page Loads in JavaScript?

How Can I Preserve Form Data Across Page Loads in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 22:28:18163browse

How Can I Preserve Form Data Across Page Loads in JavaScript?

How to Preserve Variables Between Page Loads

As HTTP is stateless, capturing form submission states between page refreshes can be challenging. Persistent storage between page loads is not easily achieved using JavaScript alone.

Query String

When submitting forms using the GET method, query strings are created (?parameter=value). By setting an input field in the form to a specific value, you can utilize the query string. For instance:

<form method="GET">
    <input type="hidden" name="clicked" value="true" />
    <input type="submit" />
</form>

On form submission, the query string updates to include the clicked parameter. When the page reloads, you can check the query string to determine if the submit button was clicked.

Web Storage

HTML5 provides Web Storage, allowing data to be saved in the browser across page loads. LocalStorage stores data indefinitely, while SessionStorage only retains data during the current browsing session. For this purpose, SessionStorage is appropriate:

$('input[type="submit"][value="Search"]').click(function() {
    sessionStorage.setItem('clicked', 'true');
});

Cookies

Cookies can also store data client-side. Using jQuery, you can set cookies easily:

$('input[type="submit"][value="Search"]').click(function() {
    $.cookie('clicked', 'true', { expires: 1 }); // expires in 1 day
});

Window.name

As a hackish approach, you can store data in the window.name property:

window.name = JSON.stringify({ clicked: true });

This approach is restricted to the current tab and only stores strings.

The above is the detailed content of How Can I Preserve Form Data Across Page Loads in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn