Change action attribute of form using JavaScript in Rails

Hello everyone,

I had a situation where I’ve more than one submit buttons in a form
which I need to send data to different controllers’ action. From my
previous posts I got a suggestion to use JavaScript.

**Please Note: I’m not looking forward to detect which button is pressed
and redirect according to it.

Here is my code.

view
<%= form_tag “#”, :id => “multi_cont_form” do %>

<%= label_tag(“From date”) %>
<%= date_field_tag ‘fdate’, Date.today, :autofocus =>true, class:
‘form-control’ %>

   <div class="actions">
    <%= button_tag "Test JS", :onclick =>

“sendParams(‘receipt_rpts_create_path’)” %>

   <div class="actions">

<%= button_tag “Test JS”, :onclick =>
“sendParams(‘payments_rpts_create_path’)” %>

<% end %>

(I’ve only showed two buttons for example purpose.)

JavaScript (Corrected)

function sendParams(newAction)
{
var mem_code = document.getElementById(“member_code”).value;
var x = document.getElementById(“multi_cont_form”).action;
document.getElementById(“multi_cont_form”).setAttribute(“action”, “”);
console.log("Checking form action received " + newAction + “…”);
console.log("Current form action " + x + “…”);
document.getElementById(“multi_cont_form”).setAttribute(“action”,
newAction);
var x = document.getElementById(“multi_cont_form”).action;
console.log("New action " + x + “…”);
alert("New action of form is " + x);
document.getElementById(“multi_cont_form”).submit();
}

Even after I reset action attribute to “” and reassigned with new given
action, the final URL is being prefixed with current page’s URL.

For eg:
If current page URL is “localhost:3000/reports/new”
The newly created form action using JS is
“localhost:3000/reports/receipt_rpts_create_path”

I can’t prevent that “reports” from being prefixed.
And even “receipt_rpts_create_path” is not converted to
receipt_rpts/create URL.

Technically how to change “controller” option’s value and “action”
option’s value of <% form_tag %> helper using JavaScript. If its not
possible how to achieve it using JS.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs