Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - change form action based on radio selection

I'm a Rails noob. I won't lie. I've been tasked with taking two forms and turning them into one dynamic form. This is a Login/Sign Up form. The only issue I have is how to handle the Rails portion of the code. Using jQuery, I could have easily replaced HTML form actions, but how would I approach replacing the action/destination in the rails code based on a login or sign up radio selection.

<%= form_tag login_path, :id => '_login_form' do %>
<% end %>

<%= form_tag sign_up_path, :id => '_sign_up_form' do %>
<% end %>
like image 813
TSNev Avatar asked Dec 27 '22 14:12

TSNev


1 Answers

I see two options to solve your problem.

Using javascript you can change the action of a form, based on the radio button selected.

$("#radio").change(function() {
  var action = $(this).val() == "some_value" ? "login" : "sign_up";
  $("#your-form").attr("action", "/" + action);
});

Or you can handle both methods in a single action and treat each of the options separatedly

#view
<p> <%= radio_button_tag :option, "login" %> Orange </p>
<p> <%= radio_button_tag  :option, "sign_up" %> Peach </p>

#controller
if params[:option] == "login"
  #do login
elsif params[:option] == "sign_up"
  #do sign up
end

I hope this helps!

like image 115
felipeclopes Avatar answered Jan 13 '23 20:01

felipeclopes