Reputation: 1181
I am explainig my problem in a simple example. I am building a recipe app. In my show partial which is loaded via AJAX I do the following:
_show.html.erb
<% @recipe.ingredients.each do |ingredient| %>
<div class="col-xs-12" id="ingredient-<%= ingredient.id %>">
<div id="amount-<%= ingredient.id %>"><%= ingredient.amount %></div>
<%= ingredient.unit.unit_name %>
<%= ingredient.ingredient_name %>
</div>
<% end %>
This gives me a list like:
What I want to do now (just in my example) is to replace each amount value with the phrase "Hi, it's me!". Therefore I thought I could use the following jquery (I am not using Turbolinks) in my partial to get the dynamic id from the each block:
$( document ).ready(function() {
$('#amount-<%= ingredient.id %>').html("Hi, it's me!");
});
I expect the list to be:
However, it does not work and I don't understand what am I doing wrong? If I use a static id or a static class it works. However (for some calculations I want to perform with each amount), I need it dynamic based on <%= ingredient.id %>
.
Upvotes: 0
Views: 987
Reputation: 1181
Ok, I found my error. Stupid mistake though. I have to put the jquery part inside the each do block. Otherwise, of course, <%= ingredient.id %> is not defined.
Solution looks now like this:
<% @recipe.ingredients.each do |ingredient| %>
<div class="col-xs-12" id="ingredient-<%= ingredient.id %>">
<div id="amount-<%= ingredient.id %>"><%= ingredient.amount %></div>
<%= ingredient.unit.unit_name %>
<%= ingredient.ingredient_name %>
</div>
<script>
$('#amount-<%= ingredient.id %>').html("Hi, it's me!");
</script>
<% end %>
Upvotes: 1