提交表单后设置指定输入框永久只读及解决刷新数据丢失问题
Hey Paul, let's tackle your two linked issues here: keeping submitted data visible after page refreshes, and making those specific fields permanently read-only once submitted. Since you already have MySQL saving the data, we just need to tie that backend data back to the frontend and lock down the fields properly.
1. Fixing Data Disappearing After Refresh
The root issue here is that your page isn't pulling the saved data from MySQL when it loads. You need to populate the form fields with the existing database values on page render (or initial load for SPAs).
Server-Side Rendering Example (e.g., PHP, Python Django)
If you're using server-side rendering, fetch the saved record from your database before rendering the form, then inject the values into the input fields. For your "Last Name" field:
<div class="form-group"> <label class="control-label col-sm-2" for="lname">Last Name*</label> <div class="col-sm-10"> <input type="text" class="form-control" id="lname" name="lname" <!-- Inject the saved value from MySQL; use htmlspecialchars to prevent XSS --> value="<?php echo htmlspecialchars($savedRecord['last_name'] ?? ''); ?>" /> </div> </div>
Replace $savedRecord with your backend's variable that holds the fetched MySQL data.
Frontend-First (SPA) Example
If you're using a single-page app (React, Vue, vanilla JS), make an API call on page/component load to fetch the saved data, then populate the fields:
// Example with vanilla JS async function loadSavedData() { const response = await fetch('/api/get-saved-form-data'); const savedData = await response.json(); const lastNameField = document.getElementById('lname'); lastNameField.value = savedData.last_name || ''; } // Call this when the page loads window.addEventListener('DOMContentLoaded', loadSavedData);
2. Making Fields Permanently Read-Only
You need two layers of protection here: frontend UX (to prevent accidental edits) and backend validation (to block malicious attempts to modify the data).
Frontend Lockdown
Once the field has a saved value, add the readonly attribute to the input. This prevents user edits and keeps the value submitable (unlike disabled, which excludes the field from form submissions).
Update your server-rendered code to conditionally add the attribute:
<input type="text" class="form-control" id="lname" name="lname" value="<?php echo htmlspecialchars($savedRecord['last_name'] ?? ''); ?>" <!-- Only add readonly if the field has a saved value --> <?php echo !empty($savedRecord['last_name']) ? 'readonly' : ''; ?> />
For SPAs, set the attribute dynamically after loading data:
if (savedData.last_name) { lastNameField.setAttribute('readonly', true); // Optional: Add visual cues to indicate read-only state lastNameField.style.opacity = 0.7; lastNameField.style.cursor = 'not-allowed'; }
Backend Validation (Critical!)
Frontend readonly can be bypassed with browser dev tools, so you must enforce the restriction on the backend. When processing form submissions:
- Check if the field already has a value in MySQL.
- If it does, ignore the new value from the form and keep the existing one.
Example MySQL update query (using parameterized queries to prevent SQL injection):
UPDATE your_form_table SET last_name = IF(last_name IS NOT NULL, last_name, :submitted_last_name), -- Apply this logic to all fields you want to lock other_field = IF(other_field IS NOT NULL, other_field, :submitted_other_field) WHERE record_id = :record_id;
This query only updates the field if it's currently empty; if a value already exists, it leaves it untouched.
3. Key Notes
- XSS Protection: Always escape user-submitted data when injecting it into HTML (like using
htmlspecialcharsin PHP) to prevent cross-site scripting attacks. - Record Identification: Make sure you're fetching the correct record from MySQL (use a user ID, session ID, or unique form token to match the user to their submitted data).
- User Feedback: Consider adding a tooltip or message next to read-only fields explaining why they can't be edited (e.g., "This field is locked after submission").
内容的提问来源于stack exchange,提问作者Paul

