Reputation: 441
I have a onclick calling searchSymbol() which works perfectly fine on the first attempt. However, it only works once. What do I need to do in order to make sure my alert(tickerSymbol) is working multiple times? I am changing the "Ticker" value each buttonClick by textField.
HTML
<input type="text" id="searchTicker" placeholder="Ticker Symbol..." required>
<input type="button" id="searchButton" onclick=searchSymbol() required>
<script type="text/javascript" id="myScript"></script>
.js
function searchSymbol() {
var ticker = document.getElementById("searchTicker").value;
document.getElementById('searchTicker').value='';
var url="http://ir.stockpr.com/service/quote_jsonp?symbol=";
var extra="&jsonp=quote_search";
document.getElementById('myScript').src = url+ticker+extra;
}
function quote_search(json) {
var tickerSymbol = json.symbol
alert(tickerSymbol)
}
This alert will only work on the first click of my button. Im not sure what I am doing wrong.
alert(tickerSymbol)
Upvotes: 1
Views: 94
Reputation: 1521
Changing the src of a script tag won't make it GET the new src. You would have to GET the JSONP programatically by creating a new script tag, like this:
function searchSymbol() {
var ticker = document.getElementById("searchTicker").value;
document.getElementById('searchTicker').value='';
var url="https://ir.stockpr.com/service/quote_jsonp?symbol=";
var extra="&jsonp=quote_search";
// Remove already existing script tag
if(document.getElementById('myScript'))
document.getElementById('myScript').parentNode.removeChild(document.getElementById('myScript'));
// Create script tag and add it to head
var script = document.createElement('script');
script.src = url+ticker+extra;
script.id = 'myScript';
document.head.appendChild(script)
}
function quote_search(json) {
// Check if we get anything in response
if(json && json.symbol){
var tickerSymbol = json.symbol
alert(tickerSymbol)
}
}
Upvotes: 2
Reputation: 782107
I don't think that assigning the src
of a script will cause it to reload. You need to create a new script tag.
function searchSymbol() {
var ticker = document.getElementById("searchTicker").value;
document.getElementById('searchTicker').value='';
var url="http://ir.stockpr.com/service/quote_jsonp?symbol=";
var extra="&jsonp=quote_search";
var newscript = document.createElement("script");
newscript.src = url+ticker+extra;
document.head.appendChild(newscript);
}
Upvotes: 1