Dynamically insert params to link_to in Rails
ajax, ruby-on-rails, submit
Solution
You can't. Your javascript can't hack into your server-side code. However, it can hack the result of your server-side code, which is HTML.
To make sure the query for your posts link matches properly, you should add a specific ID to your `<%= link_to %>`:
<%= link_to "Search", posts_path, :id => "search_link" %>
Then your javascript should be like:
$("#my_input").change(function() {
$("#search_link").attr("href","/posts?q=" + encodeURIComponent( $(this).val() ) );
});
Thanks to user @beck03076 for suggesting that you could simply execute a location change on click rather than updating the link every time the input changes:
$("#link").click(function() {
$(this).attr("href", "/posts?q=" + encodeURIComponent($("#my_input").val()));
});
Depending on what exactly you want to do, this may not exactly match your expectation. For example, if you have some other code that inspects the link URL to update something else on the page, this second method won't work. If, on the other hand, all you want is to execute a search on click, this will be much more efficient.
Problem
In my homepage, I have an input box that user can type in a search query. Then I have a link_to which will make a get request to a different page (search page) with the search query. By design, I can't use Rails form_for. How can I insert my query dynamically to "link_to" after detecting a change in my input box? Here is a mock: ``` %input{:type => "text", :id => "my_input"} = link_to "Search", posts_path(query: "my_query_here") :javascript $(function(){ $("#my_input").change(function() { ... do something here ... }); }); ``` Thank you.