views:

69

answers:

3

I need to create a 'Reply' button that shows a form for any item in a feed. In other words, it can't be showing/hiding something with a unique div id, because it has to work for any of a (potentially) infinite number of items.

If I use code like this:

<% @questions.each do |question| %>
  <%= question.content %>
  <a href="" onclick="showStuff('reply'); return false;">Reply</a>
  <div id="reply">
    <% form_for @reply do |f| %>
      <%= f.text_field :message %>
      <%= f.submit "Add", :class => "button" %>
    <% end %>
  </div>
  <% end %>

then the form only opens for the first item in the feed.

I don't know Javascript at all and not much JQuery, but if someone wants to take me through this step-by-step, I'd really appreciate it. Thanks.

A: 

Use jquery, and use classes.

NimChimpsky
A: 

As you are generating multiple elements, you shouldn't give them an id, because each id should be unique.

Instead, locate the div by searching relative to the link that was clicked on.

<% @questions.each do |question| %> 
    <%= question.content %> 
    <a href="" onclick="showStuff(this); return false;">Reply</a> 
    <div> 
       <% form_for @reply do |f| %> 
           <%= f.text_field :message %> 
           <%= f.submit "Add", :class => "button" %> 
       <% end %> 
    </div> 
<% end %> 
.
.
.
function showStuff(link){
   $link).next().show();
}
belugabob
hm, so I can just replace: function showStuff(id) { document.getElementById(id).style.display = 'block'; }with function showStuff(link){ $link).next().show(); }.....(that $ indicates JQuery, right? Do I just take it out if I'm not using JQuery?)
kateray
Yes, the $ indicates jQuery. Although you don't have to use jQuery, if you are using any kind of javascript, then jQuery, prototype or any one of the other libraries that are out there will help you immensely. sosborn suggested dynamically generating unique id value and, whilst this is possible, it's just not needed in this case - $(link) gets a jQuery object that refers to the link that was clicked on, .next() gets the next element in the DOM (the div, in this case) and .show() is effectively a shortcut for style.display='block'. Give jQuery a try - you won't regret it.
belugabob
+1  A: 

I don't see why it isn't possible to give unique IDs. Just do something like this in your loop:

<div id="reply_<%= question.id %>">

Now all of your divs will have unique IDs. Furthermore, it is easy to know what div ID references which question because you know which questions (and corresponding IDs) you pulled from the database.

sosborn