All,
I have a website that fetches a list of publicly-traded companies from an API endpoint. I take that returned JSON data to then populate a dropdown element called, “mySelect”, with the company stock ticker symbols. I need to do two things:
-
Pass the first company’s symbol that gets populated in the dropdown menu to a query parameter in a URL that will then fetch the price data for that company so that I can display it on a chart.
-
Change the symbol that gets passed to that price data URL from the first company’s symbol that gets loaded when the page loads, to the symbol of the company that is selected from the dropdown menu.
I’m struggling to figure out how to do this in the same script. I’d previously had two different javascript files – one that grabs the first value on page load, and the second grabbed the selected company value. This seemed really duplicative. Not sure why I can’t wrap my head around how to pass these values dynamically to the second URL. Any guidance would be appreciated. I’m happy to provide additional information. Thanks!
Sample abridged code:
// function to handle fetches:
function getCompanies(url) {
return fetch(url)
.then(response => {
if(!response.ok) {
throw new Error('Bad Network Request');
}
return response.json();
})
.catch(error => {
console.error('Fetch error:', error);
throw error;
});
}
// use the getCompanies function to fetch the list of companies from an API endpoint and populate a dropdown menu on the webpage:
getCompanies('/api/company_list')
.then(function fetchData(data) {
let option = '';
for (let i = 0; i < data.length; i++) {
option += '<option value="' + data[i].symbol + '">' + data[i].stock_rank + ' - ' + data[i].company_name + ' (' + data[i].symbol + ')' + '</option>';
}
$('#mySelect').append(option);
})
.catch(error => {
console.error('Error:', error);
});
// use the getCompanies function to fetch the pricing data for the symbol selected in the dropdown menu:
getCompanies(`/api/prices?symbol=${symbol}`)
.then(function chartData(data) {
//do something with the data...
})
document.getElementById("mySelect").onchange = function () {getSymbol()};
// store the selected company symbol as the variable "myVal" (need to pass this to the stock price URL)
function getSymbol() {
var myVal = $("#mySelect").val();
return myVal;
}