JavaScript Array Problem

Could you please review the code below and help me understand why I am encountering issues when trying to run the program?


 $(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');
        });
    }
}

Could the issue be related to my Array object, or are there other parts of the program that may have problems? It's worth noting that the code runs smoothly without referring to the array elements.

Thank you

Answer №1

Your curly braces, round brackets, square brackets, and parentheses do not all match up correctly. Additionally, for your function to access the comp variable, they must both be within the same function scope, like so: $(document).ready(function(){ ... });. I've also adjusted the setInterval to 2000 (2s).

VIEW 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');
       });
      }
    }
});​

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an object using JSON and implementing custom methods in Javascript

When making a $.ajax request to an API, I receive a chunk of JSON data. The JSON looks something like this: var result = { "status": 200, "offset": 5, "limit": 25, "total": 7, "url": "/v2/api/dataset/topten?", "results": [ { "d ...

Invoking the HTML method from a WCF service

Currently, I am utilizing a callback in my WCF service to receive raw frames from the camera. I am currently working on developing an HTML application that will showcase these frames. However, my current approach involves using a button click event in HTM ...

Is it possible for the number returned by setTimeout() in JavaScript to be negative?

Is it possible for a number returned by the setTimeout() function in JavaScript to be negative? Currently, I've observed that the timeoutIds generated are sequentially numbered in Chrome as 1,2,3,4,5,6... While in Firefox, they start from number 4 an ...

The `getScript` function in jQuery is not working as expected, even though the path is accurate and the script was successfully downloaded

Recently, I created a website using Mustache.js and incorporated templates loaded via AJAX with jQuery. During the testing phase on my local environment, everything worked perfectly. However, upon uploading the site to my school server, an issue arose whe ...

Jackson version 2.6.5 is dismissing the SerializationFeature.INDENT_OUTPUT setting

I have been using Jackson mapper version 2.6.5 in combination with Spring Boot, but I am unable to make SerializationFeature.INDENT_OUTPUT work as expected. I have been following the tutorial provided here. Below is a snippet of my code: public class Seri ...

Tips for Showing Websocket Response On Web Browser Using Node.js

Just starting out with NodeJS and here's my code snippet: const webSocket= require('ws'); const express = require('express'); const app=express(); Var url = "wss://stream.binance.com:9443/BTCUSDT@trade`" const ws = new webS ...

How can we dynamically resize page content to fit varying browser window sizes across different devices with the help of jQuery/JavaScript?

Looking for a solution involving an HTML form that includes a text field and a submit button. The text field is where the user enters a URL, and upon clicking the submit button, they are redirected to that URL. Seeking a way to adjust the size of the new ...

It appears that the jQuery.post() method is being overlooked or bypassed for unknown reasons

Trying to understand why the call to jQuery.post() isn't fetching the data or running the function after the fetch. Three files are included: an HTML file, a JavaScript file, and a PHP file. The HTML contains the modal element intended to appear when ...

Sharing information between sibling modules

Currently, I am faced with the challenge of transmitting data between two sibling components within the following component structure. The goal is to pass data without changing the relationships between these components. I prefer not to alter the componen ...

What is the syntax for invoking a function within a nested function in TypeScript?

Is there a way to call the function func2 from within the sample function of function func1? Any suggestions on how to achieve that? class A { public func1() { let sample = function() { //call func2... but ...

Enhance your React Routing using a Switch Statement

I am currently developing a React application where two distinct user groups can sign in using Firebase authentication. It is required that each user group has access to different routes. Although the groups share some URLs, they should display different ...

The mobile devices are not showing my HTML website

I have implemented the following CSS link code on my website: <link rel="stylesheet" href="index_files/front.css" media="all" type="text/css" > Additionally, I have included the following code <meta name="HandheldFriendly" content="True"> & ...

Troubleshooting a malfunctioning ember.js HTML output

I'm currently facing a challenging debugging task to figure out why this specific code snippet is failing: Here is the template causing issues: <p class='navbar-text pull-right header-user-info'> {{#if currentUser.isSignedIn}} {{#i ...

Avoid showing images when the link is not working

I am dynamically fetching images and displaying them on my webpage. return <div className="overflow-hidden "> <Image className="relative w-full h-40 object-cover rounded-t-md" src={cover_url} alt={data.name} ...

What is causing my fetch response to not be passed through my dispatch function?

I'm currently utilizing a node server to act as the middleman between firebase and my react native app. Could someone kindly point out what might be going awry in my fetch method below? export const fetchPostsByNewest = () => { return (dispatch ...

Tips for sending a Django queryset as an AJAX HttpResponse

Currently, I am faced with the challenge of fetching a Django queryset and storing it in a JavaScript variable using Ajax. I have attempted to employ the following code snippet for this purpose; however, I keep encountering the issue of "Queryset is not J ...

Issue encountered while attempting to attach an event listener to an element within a class

Upon running the code, I encountered an error message that reads: Uncaught TypeError: this.startButton.addEventListener is not a function and I'm unsure of how to resolve it. Although I can successfully console.log the button inside the class, adding ...

Error: Unable to execute function on blog mapping

I am facing an issue with my app where it fails to detect objects. Every time the component in my app calls ".map", I encounter an error message. I have double-checked that index.js is passing props correctly. Can anyone explain why this problem is occurri ...

What steps can be taken to retrieve data from a database table using JavaScript?

I am encountering a very peculiar issue. The values that I need are visible when I receive them as a message from the server-web console. However, when I try to retrieve them using a for loop, I encounter an error 05-22 18:58:23.203: I/Web Console(29392): ...

Is there a way in JavaScript to activate a web element by clicking on its center?

I have a webpage and I'm looking to simulate clicks using the console. I attempted to do so with the code snippet document.getElementById("myButtonId").click(), but it seems that the element only responds to clicks at its center location. Is there ano ...