Keep input value after refresh page

Keep input value after refresh page

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Keep input value after refresh page

When a user starts filling out a form, enters some data into a text field, and then navigates away to add new options to a dropdown list populated from a database, the natural expectation is that their progress shouldn't vanish upon returning. The core challenge here isn't just about "saving" data; it's about maintaining state across multiple HTTP requests without triggering a full form submission or relying on complex server-side sessions for simple UI persistence.

The scenario described involves two distinct pages: a primary page with a text input and a dynamic dropdown (<select>), and a secondary page where new labels are added to the database. When the user moves from the first page to the second, they are effectively abandoning the current form state in the browser's memory. The standard HTML behavior is that refreshing or navigating away clears the input fields unless specific mechanisms are in place.

To solve this, you need to understand the lifecycle of the HTTP request-response cycle. When a user clicks a link or uses the browser's back button to return from the "Add Label" page to the main form page, the browser does not automatically retrieve the previous state of the input fields (txt_name and txt_label). It loads the raw HTML defined in the server response. Therefore, the solution must involve intercepting this navigation or explicitly restoring the data upon the initial load of the form.

Implementing State Persistence with JavaScript

The most robust and modern approach to handling this without a full page refresh or complex session variables is to use client-side state management. You can store the user's input in localStorage before they navigate away and restore it when they return. This keeps the logic on the client side, reducing server load for simple UI states.

On the first page, you need to modify your HTML inputs slightly to ensure they have unique attributes for selection and add a script that handles the restoration. Here is how you can structure the form:

<form name="mainForm" method="post" action="">
    <input name="txt_name" id="user_name" type="text" />
    
    <select id="groups" name="txt_label" class="form-control">
        <!-- Dynamic options loaded via PHP -->
    </select>
</form>

<script>
    // Restore data when the page loads
    document.addEventListener('DOMContentLoaded', function() {
        const savedName = localStorage.getItem('saved_user_name');
        const savedLabel = localStorage.getItem('saved_txt_label');

        if (savedName) {
            document.getElementById('user_name').value = savedName;
        }

        // Note: If the saved label exists in the database, you must also 
        // populate the select element. This requires fetching the current DB state
        // and matching it against the saved value.
        if (savedLabel) {
            const selectElement = document.getElementById('groups');
            // Logic to find the option with this value and select it goes here
        }
    });

    // Save data before leaving the page
    window.addEventListener('beforeunload', function() {
        localStorage.setItem('saved_user_name', document.getElementById('user_name').value);
        localStorage.setItem('saved_txt_label', document.getElementById('groups').value);
    });
</script>

The Challenge of Dynamic Dropdowns

The text input is straightforward; you just read the value from localStorage and write it back. However, the dropdown (<select>) presents a specific pitfall: data integrity.

When the user returns to the first page after adding new info on the second page, the PHP code that fetches DISTINCT db_label from tbl_label will now include the newly added rows. If you simply restore the saved value into the <select> element, it might not appear as an "selected" option if your database logic or the user's action changed the underlying data structure in a way that breaks the match.

For example, if the user saves "Label A", goes to add "Label B", and returns, the dropdown will now contain both "Label A" and "Label B". Your JavaScript needs to not only set the text value but also iterate through the <option> tags to find the one matching the saved value and apply the selected attribute.

if (savedLabel) {
    const selectElement = document.getElementById('groups');
    
    // Clear existing selections if necessary, or just ensure the target is selected
    Array.from(selectElement.options).forEach(option => {
        option.selected = false;
    });

    const savedOption = selectElement.querySelector(`option[value="${savedLabel}"]`);
    if (savedOption) {
        savedOption.selected = true;
    } else {
        // Handle case where the saved value is no longer in the dropdown
        console.warn('Saved label not found in current options.');
    }
}

Trade-offs and Considerations

Using localStorage is generally preferred over hidden fields or server-side sessions for this specific use case because it persists even if the user closes the browser and reopens it later, provided they don't clear their cache. However, there are limitations:

  1. Storage Limits: Browsers limit localStorage size (usually around 5-10MB). For a simple text field and dropdown value, this is irrelevant, but keep it in mind for larger projects.
  2. Cross-Origin Issues: If your first and second pages are hosted on different domains, localStorage won't share data between them unless you handle CORS carefully. In the provided snippets, both forms seem to be part of the same application (using $_PHP_SELF), so this is likely not an issue.
  3. Security: Never store sensitive data in client-side storage without encryption, though label names are generally safe.

If you are building a larger application using the Laravel framework, you might consider using Laravel's session facade or a dedicated state management library like Alpine.js or Vue to handle this logic more declaratively, but for vanilla PHP and jQuery-free solutions, the localStorage approach is efficient and requires minimal backend changes.

Our network