Search code examples
ruby-on-railshidden-fieldlink-to

How to pass values from hidden_field_tag through link_to params (Rails)


I would like to click on a link and pass in a value from an existing hidden_field_tag (which is updated on multiple occasions in other events) in a simple_form.

Here is some sample code:

= hidden_field_tag :tag_value, "starting_value", id:"tag_id"
...

=link_to "Submit", controller_method_path(value1: @id, value2: **not sure what comes here but should be :tag_value**), remote: true, method: :get

I'm not sure what syntax I should be using to get the value of the hidden tag.

Thanks in advance.


Solution

  • Attach a click event to "submit" and use a mask as value2:

    =link_to "Submit", controller_method_path(value1: @id, value2: "#####"),onclick: "change_action()", remote: true, method: :get
    

    Then, write the javascript function to handle the click event:

    function change_action() {
        // If your form is unique on the page and it has no id:
        var tag_value = document.getElementById('tag_id').value;
        document.forms[0].action = document.forms[0].action.replace("#####",tag_value);
    }