How do I create a link of this type:
<a href="#" onclick="document.getElementById('search').value=this.value">
using method link_to
in Rails?
I couldn't figure it out from Rails docs.
rubyruby-on-rails
How do I create a link of this type:
<a href="#" onclick="document.getElementById('search').value=this.value">
using method link_to
in Rails?
I couldn't figure it out from Rails docs.
Best Solution
You can use
link_to_function
(removed in Rails 4.1):Or, if you absolutely need to use
link_to
:However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.
Instead, your Rails code should simply be something like this:
And assuming you're using the Prototype JS framework, JS like this in your
application.js
:Or if you're using jQuery:
By using this third technique, you guarantee that the link will follow through to some other page—not just fail silently—if JavaScript is unavailable for the user. Remember, JS could be unavailable because the user has a poor internet connection (e.g., mobile device, public wifi), the user or user's sysadmin disabled it, or an unexpected JS error occurred (i.e., developer error).