I have a multi-step form (a wizard) that I created using this railscast: http://railscasts.com/episodes/217-multistep-forms.
A session is being used to remember all the info entered in the form. On one form page, I have a select box that has 3 options, and each option displays different form fields on the page. The options are: “Retail and Office” (both the retail and office fields are shown), “Office only” (only the office field is shown), “Retail only” (only the retail field is shown).
I used jquery to show and hide these fields based on the option selected in the select box. So here’s the problem I’m having. Let’s say, for example, that I’ve selected “Retail only” from the select box. The office field disappears, and only the retail field is shown. I enter the info into the field, and then proceed to the next step. However, when I hit the back button to go back to this step to edit it, both the office and retail fields are shown. The “Retail only” selection in the select box remains the same, and the info I entered is still there, but both fields are being shown.
I’m assuming that the problem is with the jquery, and not the rails session. Does this have to do with cookies? How do I correct this?
application.js
$(document).ready(function() {
$("#spaces").change(function(){
if ($("#spaces").val()=="Retail only") {$("#office_field").hide(); $("#retail_field").show(); }
if ($("#spaces").val()=="Office only") {$("#office_field").show(); $("#retail_field").hide(); }
if ($("#spaces").val()=="Retail and Office") {$("#office_field").show(); $("#retail_field").show(); }
});
uploads_controller.rb
class UploadsController < ApplicationController
def index
@uploads = Upload.all
end
def show
@upload = Upload.find(params[:id])
end
def new
session[:upload_params] ||= {}
@upload = Upload.new(session[:upload_params])
@upload.current_step = session[:upload_step]
end
def create
session[:upload_params].deep_merge!(params[:upload]) if params[:upload]
@upload = Upload.new(session[:upload_params])
@upload.current_step = session[:upload_step]
if @upload.valid?
if params[:back_button]
@upload.previous_step
elsif @upload.last_step?
@upload.save if @upload.all_valid?
else
@upload.next_step
end
session[:upload_step] = @upload.current_step
end
if @upload.new_record?
render "new"
else
session[:upload_step] = session[:upload_params] = nil
flash[:notice] = "Upload saved"
redirect_to @upload
end
end
end
In your application.js you only have a ‘change’ event listener. What you need is to trigger
Your code to show/hide specific inputs is only bound to ‘change’ event of #spaces.
Basically, you need to move this code into a function, and call this function on both page load and #spaces ‘change’:
It has nothing to do with sessions.