Reputation: 35
I have a ruby each method below that has a button onclick embedded in it that I am trying to get to make a call to iex's stats api for each stock inside the portfolio when the ticker is clicked and store that in a table i have built. Here is the ruby:
<% portfolio.assignments.each_with_index do |a, index|%>
<div class="accordion" id="accordionExample">
<div>
<div id="headingThree">
<h5 class="mb-0">
<button onclick="getStock();" class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseThree<%=a.id%>" aria-expanded="false" aria-controls="collapseThree<%=a.id%>">
<li class="list-inline-item"id="<%=a.stock.ticker%>"><%= a.stock.ticker %></li>
parts of the code is missing but i just included the parts that i thought were relevant but when i run the code and inspect it in the browser i can see that everything is loading correctly for each ticker stored in the db but it only shows the data return for the first ticker?
function getStock() {
$('#<%=a.stock.ticker%>').each(function(){
var theURL = `https://api.iextrading.com/1.0/stock/<%=a.stock.ticker%>/stats`;
$.getJSON(theURL, function(data) {
var obj = data;
document.getElementById("symbol").innerHTML = obj.symbol;
});
})
};
here is part of the table i have:
<table class="table table-hover text-left">
<tbody>
<tr>
<th>Symbol:</th>
<td id="symbol"></td>
Upvotes: 0
Views: 78
Reputation: 5552
You have n
assignments and by each_with_index
, you will get n
numbers of div
calling getStock()
for n
number of times.
But actual problem is your JavaScript function getStock()
is single copy and it is not repeated to find each assignment ticker for a loop.
Just replace following,
"getStock();"
with,
"getStock(#{a.stock.ticker});"
And modify function as,
function getStock(ticker) {
$(ticker).each(function(){
var theURL = `https://api.iextrading.com/1.0/stock/' + ticker + '/stats`;
$.getJSON(theURL, function(data) {
var obj = data;
document.getElementById("symbol").innerHTML = obj.symbol;
});
})
};
Update - In case above does not work, you may try this & update function.
Upvotes: 1