Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call jQuery function from Rails link_to

I have a ruby loop that creates a list of comments..

I wonder if I can attach jQuery function to Rails link_to helper in this case?

    <% @video.phrases.each do |phrase| %> 
    <div class = "span4" id ="comment" ><%= phrase.content %></div><a id ="ff"  ><%= image_tag("ff.png", :size=> "32x32" )%></a>
    <% end %>

I am hoping for something like

    <% @video.phrases.each do |phrase| %> 
    <div class = "span4" id ="comment" ><%= phrase.content %></div><%= link_to (image_tag("ff.png", :size=> "32x32" ), html => {<script>$("#video_div").html('CONTENTS OF HTML');</script>} :remote => true %>
    <% end %>

I know it won't work, but I wonder is there an easy way to achieve this kind of functionality?

Thanks!

like image 898
Stpn Avatar asked Apr 13 '12 02:04

Stpn


2 Answers

You can do this two ways.

The first is the add an html attribute on the link_to:

<% @video.phrases.each do |phrase| %> 
  <div class = "span4" id ="comment" >
    <%= phrase.content %>
  </div>
  <%= link_to (image_tag("ff.png", :size=> "32x32" ), html => {:onclick => "$('#video_div').html('CONTENTS OF HTML');"} :remote => true %>
<% end %>

The second is to separate the Javascript from Ruby:

<% @video.phrases.each do |phrase| %> 
  <div class = "span4" id ="comment" >
    <%= phrase.content %>
  </div>
  <%= link_to (image_tag("ff.png", :size=> "32x32" ) :remote => true %>
<% end %>

<script type="text/javascript">
  $('a').click(function(){
    $("#video_div").html('CONTENTS OF HTML');
  );
</script>

If you want the contents of the link tag, substitute 'CONTENTS OF HTML' for $(this).html()

like image 136
grant Avatar answered Oct 07 '22 05:10

grant


Also I actually found out about Rails link_to_function helper and was able to achieve the desired behavior with:

<% @video.phrases.each do |phrase| %> 
 <div class = "span4" id ="comment" ><%= phrase.content %></div><a id ="ff">
  <%= link_to_function image_tag("ff.png", :size=> "32x32" ), "use_comment('#{phrase.comment}')"%>
 </a>
like image 37
Stpn Avatar answered Oct 07 '22 05:10

Stpn