views:

2258

answers:

2

Hi there. I have a small problem. How to create a link of this type:

a href="#" onClick="document.getElementById('search').value=this.value"

using method 'link_to' in Rails?

P.S. I write http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html, but I can not imagine how to make such a link.

+14  A: 

You can use link_to_function:

link_to_function 'My link with obtrusive JavaScript', 'alert("Oh no!")'

Or, if you absolutely need to use link_to:

link_to 'Another link with obtrusive JavaScript', '#',
        :onclick => 'alert("Please no!")'

However, putting JavaScript right into your generated HTML is obtrusive, and is bad practice.

Instead, your Rails code should simply be something like this:

link_to 'Link with unobtrusive JavaScript',
        '/actual/url/in/case/user/doesnt/have/javascript/enabled',
        :id => 'my-link'

And assuming you're using the Prototype JS framework, JS like this in your application.js:

$('my-link').observe('click', function(event){
  alert('Hooray!');
  event.stop(); // Prevent link from following through to its given href
});

Or if you're using jQuery:

$('#my-link').click(function(event){
  alert('Hooray!');
  event.preventDefault(); // Prevent link from following its href
});

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 or user's sysadmin disabled it, an unexpected JS error occurred (i.e., developer error), or the user has a poor internet connection (e.g., mobile device, airport).

Ron DeVera
Thanks, Ron. I try second example - works fine.
Yud
A: 

Hi i tried the above javascript instead of making an alert it just passed the value as a parameter and gets suffixed to URL

What to do abt it?

jana