Rails表单提交时如何不显示地为输入字段追加字符串?
Got it, let's sort out this problem for you! The issue with your current code is that you're directly modifying the input field's value before submission, which is why users see "years old" show up in the box. We need to pass the formatted text to the next page without altering what the user sees in the input. Here are a few solid approaches:
1. Use a Hidden Field (Frontend Approach)
Add a hidden input to your form that will hold the formatted value, while keeping the visible input for user entry. This way, the user's input stays unchanged, but we send the formatted string:
First, update your Rails form:
<%= form_tag age_path, method: "POST", id: 'age', remote: true do %> <%= text_field_tag 'user_age', nil, placeholder: "Enter your age" %> <%= hidden_field_tag 'age-question' %> <!-- Hidden field for formatted value --> <%= submit_tag "Submit", id:"submit-age" %> <% end %>
Then adjust your JavaScript to populate the hidden field instead of modifying the visible input:
$('#age').submit(function() { const rawAge = $('#user_age').val().trim(); // Only populate the hidden field if there's a valid numeric input if (rawAge && !isNaN(rawAge)) { $('#age-question').val(`${rawAge} years old`); } });
2. Modify the Submission Data Directly (No Hidden Fields)
If you don't want to add extra fields, you can intercept the form's submission data and modify it before it's sent. This works well since your form uses remote: true (Rails UJS/Turbo):
// For Rails UJS $('#age').on('ajax:beforeSend', function(e, xhr, settings) { const rawAge = $('#age-question').val().trim(); if (rawAge && !isNaN(rawAge)) { // Replace the raw age value with the formatted string in the request data const formattedAge = encodeURIComponent(`${rawAge} years old`); settings.data = settings.data.replace(/age-question=[^&]+/, `age-question=${formattedAge}`); } });
This way, the input field stays exactly as the user typed it, but the server receives the formatted text.
3. Handle It in the Backend (Recommended)
Honestly, the most reliable and secure approach is to handle the formatting on the Rails backend. Let the frontend send just the raw number, then format it server-side. This prevents any tampering with the formatted string and keeps your frontend code simpler:
First, keep your original form (no JS needed here!):
<%= form_tag age_path, method: "POST", id: 'age', remote: true do %> <%= text_field_tag 'age-question', nil, placeholder: "Enter your age" %> <%= submit_tag "Submit", id:"submit-age" %> <% end %>
Then in your controller action:
def age # Get the raw age and validate it's a valid positive number raw_age = params[:age_question].to_i if raw_age > 0 formatted_age = "#{raw_age} years old" # Pass the formatted value to your next page/view @display_age = formatted_age else # Handle invalid input (e.g., show an error message) @display_age = "Please enter a valid positive age" end end
This method is better because you can add proper validation and you don't rely on frontend JS, which can be bypassed or fail if users have JS disabled.
内容的提问来源于stack exchange,提问作者Tom Bom

