0

Lets assume I have a list of objects in an array and i want each of those items to have an id, let us say data-id="<%= item.id%>" how can i pass this data-id in in JavaScrpt so that it displays an alert message with the items id.

pts
  • 80,836
  • 20
  • 110
  • 183
Uchenna
  • 4,059
  • 6
  • 40
  • 73

2 Answers2

0

I'm not sure exactly what you are asking, but if you want to iterate over an array and display alerts for each id it would look something like this:

# assuming @items is and array of objects
<% for item in @items %>
  <script>alert('<%= item.id %>')</script>
<% end %>

To address @mikeycgto's point of a ton of alerts, if you wanted to just have an alert with all the id's at once, you could do:

<script>alert('<%= @items.collect(&:id) %>')</script>

EDIT: So if you want to pass the id along and use the id inside of your item partial for your js, you can use render partial with a collection.

render :partial => 'item', :collection => @items

This will render "items/_item.erb" and pass the local variable ad to the template for display. An iteration counter will automatically be made available to the template with a name of the form partial_name_counter. In the case of the example above, the template would be item_counter.

So in your _item.erb partial you could access the item like this:

<div id="item_<%= #{item.id} %>" class="item">
  <script>document.write('this is my item id written from JS: <%= item.id %>');</script>
</div>

This would render blocks with div ids in the form of "item_" with a class item, and the js would write out the id inside the block. You can repurpose the js to do whatever you need.

Chris Barretto
  • 9,379
  • 3
  • 42
  • 45
0

If you want to actually be able to use the data you should serialize it as json

How to do Ruby object serialization using JSON

Then just pass it to a variable

<script type="text/javascript">
  var json = <%= json_serialized_object %>
</script>
Community
  • 1
  • 1
Greg Guida
  • 7,302
  • 4
  • 30
  • 40