Ruby variable evaluation in jQuery expression is passed: onclick in Rails

I am iterating over posts and want to create toggle options for posts, but I cannot replace the div-id on posts:

<% for bill in @bills %>
<% tmp = "test"%>
<%= link_to '&raquo now','#', :onclick => '$("#{tmp}").toggle();' %>

      

Instead of getting:

<a href="#" onclick="$(&quot;#test&quot;);">&raquo now</a>

      

I get:

<a href="#" onclick="$(&quot;#{tmp}&quot;).toggle();">&raquo now</a>

      

So there is no ruby โ€‹โ€‹variable estimate in the row. How can i do this?

Thanks for your help and I am new to jQuery.

+2


a source to share


1 answer


For string interpolation to work in Ruby, the string must be enclosed in double quotes , not:

:onclick => '$("#{tmp}").toggle();'

      



use one of the following options:

  • surrounds the double quoted string and escapes literal double quotes that occur in the string:

    onclick => "$(\"#{tmp}\").toggle();

  • use notation %Q

    , then you don't need to escape double quotes:

    :onclick => %Q{$("#{tmp}").toggle();}

  • use double quotes in Ruby code and single quotes in JavaScript that will be generated:

    :onclick => "$('#{tmp}'.toggle();"

+2


a source







All Articles