Issue with JavaScript Array - javascript

Can you please take a look at following code and let me know why I am not able to run the program?
enter code here
$(document).ready(function()
{
var comp=new Array("AAPL","MSFT","XRTX&");
var t = setInterval(function(){getPrice();},200);});
function getPrice() {
for (var i=0;i<comp.length;i++){
$.getJSON('https://finance.google.com/finance/info?client=ig&q='+comp[i]+'&callback=?', function(response){
var stockInfo = response[0];
var stockString = '<div id="stockprice">';
stockString += 'Candente Copper: DNT $'+''+stockInfo.l+'';
stockString += '</div>';
$('#stockprice').replaceWith(stockString);
$("#stockprice:contains('-')").addClass('red');
$("#stockprice:contains('+')").addClass('green');
}
});
}​
Is there any problem with my Array object or other parts of program has issue? Please be advised that the code works fine without calling the array elements.
Thanks

Your {s, }s, (s and )s do not all match up correctly. Also, in order for your function to have a reference to the comp variable, they must both be in the same function scope, in this case: $(document).ready(function(){ ... });. You'll notice that I also increased your setInterval to 2000 (2s).
EXAMPLE
$(document).ready(function()
{
var comp = new Array("AAPL","MSFT","XRTX&");
var t = setInterval(function(){getPrice();},2000);
function getPrice()
{
for (var i=0;i<comp.length;i++){
$.getJSON('https://finance.google.com/finance/info?client=ig&q='+comp[i]+'&callback=?', function(response){
var stockInfo = response[0];
var stockString = '<div id="stockprice">';
stockString += 'Candente Copper: DNT $'+''+stockInfo.l+'';
stockString += '</div>';
$('#stockprice').replaceWith(stockString);
$("#stockprice:contains('-')").addClass('red');
$("#stockprice:contains('+')").addClass('green');
});
}
}
});​

Related

Function within function in JavaScript - Need to understand this code:

I have below code within a function called render. How do I call the str variable value outside render function?
Also, please can you explain below code? I'm fairly new to js and head is hurting looking at the function calls having functions as a parameter.
My understanding is that app.getList is an object which takes function as a parameter? but it is not returning anything. Sorry, I'm lost here.
app.getList("FieldList", function(reply){
var str = "";
$.each(reply.qFieldList.qItems, function(index, value) {
str += value.qName + ' ';
});
console.log(str);
});
Full Code:
define(["jquery",
//mashup and extension interface
"qlik",
//add stylesheet
"text!./css/mystyle.css",
"client.utils/state",
"client.utils/routing"
],
function($, qlik, cssContent, clientState, clientRedirect) {
/*-----------------------------------------------------------------*/
// function redirect (sheetId){
// clientRedirect.goToSheet(sheetId, Object.keys(clientState.States)[clientState.state])
// }
/*-----------------------------------------------------------------*/
/*-----------------------------------------------------------------*/
var render = function($elem, layout) {
var html = '',
app = qlik.currApp();
//get list of tab objects and insert into div
app.getAppObjectList('sheet', function(arrayitem) {
//for each sheet in the app, create a list item
$.each(arrayitem.qAppObjectList.qItems, function(myindex, myvalue) {
//include the sheet id as the list item id to be used as a reference for active sheet
html += '<li id="' + myvalue.qInfo.qId + '">'; // onClick="redirect(' + value.qInfo.qId + ');
//wrap anchor tag to be used by bootstrap styling
html += '<a>';
//give the link the same name as the sheet
html += myvalue.qData.title;
html += '</a>';
html += '</li>';
});
html += '</ul></div>';
html += "<button id='myButton'> Click Me!! </button>";
console.log(arrayitem.qAppObjectList);
console.log(html);
//insert html into the extension object
return $elem.html(html);
});
/* Test Code Start from here */
app.getList("FieldList", function(reply) {
var str = "";
$.each(reply.qFieldList.qItems, function(key, value) {
str += value.qName + ' ';
});
console.log(str);
});
};
/*-----------------------------------------------------------------*/
return {
/*-----------------------------------------------------------------*/
paint: function($element, layout) {
console.count();
/*-----------------------------------------------------------------*/
$(function() {
$element.html("#myButton").click(function() {
// for(var mynum = 1; mynum <= 5; mynum++){
// alert('button test' + mynum);
// };
});
});
/*-----------------------------------------------------------------*/
render($element, layout);
/*-----------------------------------------------------------------*/
}
};
});
app.getList is probably asynchronous (meaning it runs in the background). The function you've passed to it is a callback. That function will be ran at some point in the future, once the AJAX call (or whatever asynchronous method is ran) is done.
Your callback is passed reply, which is the "return" value from getList(). You cannot access str from outside of this function. You need to do whatever code with reply and/or str in that function only.

jQuery UI accordion not working when data is refreshed

I have an HTML page in which data is being dynamically loaded into accordions. The accordion call is happening from inside a function. This function is being called at regular intervals to refresh the data. The accordion is showing correctly the first time, but getting destroyed when the data is refreshed. Here is some relevant code:
HTML:
...
<div id="itemsList"></div>
...
JavaScript:
function updateList() {
var storedStates = startSpinner(spinner, 'itemsList');
$.post('interface/getitemss.php',
function(data) {
var dataObj = $.parseJSON(data);
if(dataObj.status == 0) {
var itemDetails = dataObj['data'];
$("#itemsList").html("");
var infoLevel = getInfoLevel();
for (var i = 0; i < itemsDetails.length; i++) {
var rowContent = "<h3>";
if (item.type == 3 && item.approvals > 0) {
rowContent += "<span class='" + qaprColor + "'>";
rowContent += "<i class='icon-bell'></i>" + space + item.approvals + "</span>" + pipespace;
}
...
rowContent += "</div>";
$("#itemsList").append(rowContent);
}
$("#itemsList").accordion();
else in the code, I am using this:
var intervalTimer = setInterval(function() {updateList();}, <?php echo $interval; ?>);
This called the updateList() method regularly to update the data. The problem is, the moment this method is called, the previously-working accordion is destroyed and the data are appearing like normal HTML. Does anyone know how this could be fixed? Thanks!!
Have you tried calling destroy on the accordion before creating it again?
$("#itemsList").accordion( "destroy" );
$("#itemsList").accordion();
found in api docs

How do I display a JavaScript response in proper manner?

Below is my JavaScript code for calling the server API:
<script type='text/javascript'>
call_juvlon_api(apikey, 'getAvailableCredits', '', function(response) {
document.getElementById('show').innerHTML=response;
});
</script>
When I print the response in an HTML tag:
<h1 id='show'></h1>
I'm getting results in this format:
{"code":"200","status":"Success:Mail Credit Details","Mail Credits":"46"}
But what I want is a result like this:
<h1>code:200</h1>
<h1>status:Success:Mail Credit Details</h1>
<h1>Mail Credits:46</h1>
I tried the following, but nothing was displayed:
var obj=['show']
var tbl=$("<table/>").attr("id","mytable");
$("#div1").append(tbl);
for(var i=0;i<obj.length;i++)
{
var tr="<tr>";
var td1="<td>"+obj[i]["code"]+"</td>";
var td2="<td>"+obj[i]["status"]+"</td>";
var td3="<td>"+obj[i]["color"]+"</td></tr>";
$("#mytable").append(tr+td1+td2+td3);
}
First of all you'll need 3 h1 elements, so change the 'show' element to a div like this;
<div id='show'></div>
Then in your javascript code, access response elements by their name like this;
<script type='text/javascript'>
call_juvlon_api(apikey, 'getAvailableCredits', '', function(response) {
var obj = JSON.parse(response);
for(var prop in obj) {
document.getElementById('show').innerHTML += '<h1>' + prop + ":" + obj[prop] + '</h1>';
}
});

jQuery calling a variable that has variable inside a function

I have written my javascript too much, and now the code keeps repeating itself, whereas I lack of knowledge on how to simplify matters. I have this idea of calling variable into function, but I don't know how to call this kind of function that contains dynamic variables.
Anyone got any tips on how can I achieve this?
var container = '#content_container';
function container_load(){
var data = $(this).attr('data');
var dataObject = {command : data};
var title = '<h2 data="'+dataObject.command+'">'+
dataObject.command+'</h2>';
};
$(function(){
$('nav')on.('click', 'a', function(){
container_load();
$(container).prepend(title);
});
});
Apparently, console returned ReferenceError: Can't find variable: dataObject
There is two issue is in your code
var container = '#content_container';
var title; //title should be declare as global,same as "container" variable
function container_load(dis){
var data = dis.attr('data');
var dataObject = {command : data};
title = '<h2 data="'+dataObject.command+'">'+
dataObject.command+'</h2>';
}
$(function(){
$('nav').on('click', 'a', function(){
container_load($(this)); //you have to pass the current element
$(container).prepend(title);
});
});
Demo : Demo
Try this :
var container = '#content_container';
function container_load(currElementId){
var data = $("#"+currElementId).attr('data');
return '<h2 data="'+data+'">'+data+'</h2>';
};
$(function(){
$('nav')on.('click', 'a', function(){
var title = container_load(this.id);
$(container).prepend(title);
});
});
Here your problem is that you cannot 'this' in other function for that you need to pass it from your current function.
There seems to be few mistakes in your code, The scope is wrong and the data attribute is used not correctly I presume. I suppose this is what you wanted http://jsfiddle.net/EjEqK/2/
HTML
<nav >aaa</nav>
<div id="content_container"></div>
JS
function container_load() {
var data = $(this).data("val");
var dataObject = { command: data };
$("#content_container").prepend('<h2 data-val="' + dataObject.command + '">' + dataObject.command + '</h2>');
};
$(function () { $('nav > a').on('click', container_load); });
PS: If you don't need dataObject for anything else, directly use data
I think this will help you :
function container_load(currElement){
var data = $(currElement).attr('data');
return '<h2 data="'+data+'">'+data+'</h2>';
}
$(function(){
var container = '#content_container';
$('nav')on.('click', 'a', function(){
var title = container_load(this);
$(container).prepend(title);
});
});
You could do the following :
var container = '#content_container',
title; // make title global
function container_load() {
var data = $(this).attr('data');
var dataObject = { command: data };
title = '<h2 data="' + dataObject.command + '">' +
dataObject.command + '</h2>';
};
$(function () {
$('nav') on.('click', 'a', function () {
container_load.call(this); // bind this to container_load
$(container).prepend(title);
});
});
But you could do even better :
$(function () {
$('nav') on.('click', 'a', function () {
var data = $(this).attr('data');
$('#content_container').prepend(
'<h2 data="' + data + '">' + data + '</h2>'
);
});
});

How to pass a jquery function as a text, so it would be rendered in html and used by other script?

Hello there i got some code here;
<script type="text/javascript">
$(function(){
var playListURL = 'http://gdata.youtube.com/feeds/api/playlists/8BCDD04DE8F771B2?v=2&alt=json&callback=?';
var videoURL= 'http://www.youtube.com/watch?v=';
$.getJSON(playListURL, function(data) {
var list_data="";
$.each(data.feed.entry, function(i, item) {
var feedTitle = item.title.$t;
var feedURL = item.link[1].href;
var fragments = feedURL.split("/");
var videoID = fragments[fragments.length - 2];
var url = videoURL + videoID;
var thumb = "http://img.youtube.com/vi/"+ videoID +"/default.jpg";
HERE>>> list_data += '<button onclick="$('#bgndVideo').changeMovie('+ url +')">'+ feedTitle +'</button>';
});
$(list_data).appendTo(".playlist_elements");
});
});
</script>
This isnt working because of "$('#bgndVideo')" fragment that i need to pass as a text to be rendered in html so it looked like this in html:
<button onclick="$('#bgndVideo').changeMovie('http://www.youtube.com/watch?v=SOME_VIDEO_ID')"> Test </button>
How could i fix this so "$('#bgndVideo')" fragment would be treated as a text?
You would need to escape the 's:
list_data += '<button onclick="$(\'#bgndVideo\').changeMovie(\''+ url +'\')">'+ feedTitle +'</button>';
However, a cleaner approach might be something like this:
$list_data = $("<button>").html(feedTitle)
.click(function(){
$('#bgndVideo').changeMovie(url);
});

Categories

Resources