Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

link_to method and click event in 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.

like image 660
Yud Avatar asked Mar 30 '09 20:03

Yud


3 Answers

You can use link_to_function (removed in Rails 4.1):

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/javascript/is/broken',
        :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 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).

like image 121
13 revs, 2 users 99% Avatar answered Nov 11 '22 18:11

13 revs, 2 users 99%


To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...

$(document).ready(function() {
  $('#my-link').click(function(event){
    alert('Hooray!');
    event.preventDefault(); // Prevent link from following its href
  });
});
like image 41
Jim Morris Avatar answered Nov 11 '22 20:11

Jim Morris


just use

=link_to "link", "javascript:function()"
like image 9
Lei Wang Avatar answered Nov 11 '22 19:11

Lei Wang