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.
2 Answers
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.

- 9,379
- 3
- 42
- 45
-
that could be a lot of alerts.. perhaps console.log is better ;) – mikeycgto Jul 20 '11 at 05:01
-
1Yup, that could be a ton of alerts, but just following the question. lol – Chris Barretto Jul 20 '11 at 05:04
-
may be the question might no be clear. I assign individual ids to the items so then when you click on it, it gives a different behabiour based on its id. and the item are in a partial – Uchenna Jul 20 '11 at 21:14
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>

- 1
- 1

- 7,302
- 4
- 30
- 40