views:

54

answers:

3

I feel like there should be a simple way to do this, but I just don't know what it is. I have a list of data to display, and I want to include an AJAX "Read More" function to expand information at the bottom of each segment. To do this, I need unique div IDs within each segment. I have this code:

<% for choice in @student_choices %>
    <div id= "student_description", style="display:none;">
        <%= choice[:description]%>
    </div>
    <%= link_to_function "Read More", "Element.show("student_description")"%>
<% end %>

But since there are multiple div IDs, clicking "Read More" only displays the first one. How do I insert a variable div ID? I know how to do this in PHP, but this has me stumped. Even if we get the div ID itself to be variable, how do we get Element.show to accept a variable?

+1  A: 

You can do something like:

<% div_id = "student_description_#{choice.id}" -%>

<div id="<%= div_id -%>", style="display:none;">
    <%= choice.description %>
</div>

<%= link_to_function "Read More", "Element.show('##{div_id}')" %> 
rdeshpande
Awesome. I see what you're doing here, but it doesn't like the syntax in <%= link_to_function "Read More", "Element.show('<%= div_id -%>')" %>, throws "unterminated string meets end of file". This is the reason I was having trouble getting it to accept a variable.
jakefuentes
Edited. Since you're already within Ruby in the link_to_function argument, there's no need to do another <% %> block - just basic interpolation will do.
rdeshpande
Aahhhhh, got it. This works as long as you take the first # out of ##{div_id}. Thanks!
jakefuentes
+1  A: 

the conventional rails way to do this is to use dom_id

You can then do something like

<% for choice in @student_choices %>
    <div id="<%= dom_id(choice) %>" style="display:none;">
        <%= choice[:description]%>
    </div>
    <%= link_to_function "Read More", "Element.show('#{dom_id(choice)}')"%>
<% end %>
semanticart
A: 

Whilst you could use the given examples (which work) might i suggest using the rails function (http://api.rubyonrails.org/classes/ActionView/Helpers/RecordTagHelper.html ). Then on the button/link you just find the nearest div with a certain class and pull the id and do your display logic.

David Lyod