Search code examples
jquerycssjsonhtmlxmlhttprequest

Variable color not changing based on Value


I am trying to assign color to HTML variable based on value. The value is getting picked fine from JSON but the color is not changing.

Here is the script to call the variable and assign the value:

<script>
  var xmlcurrgct = new XMLHttpRequest();
  var urlcurrgct = "../json/currgct.json";
  xmlcurrgct.onreadystatechange = function() {
    if (xmlcurrgct.readyState == 4 && xmlcurrgct.status == 200) {
      console.log("xmlcurrgct.responseText", xmlcurrgct.responseText);
      var obj1 = JSON.parse(xmlcurrgct.responseText);
      console.log("obj1", obj1);
      document.getElementById("currgct").innerHTML = obj1.text.currgct;
    }
  }
  xmlcurrgct.open("GET", urlcurrgct, true);


  var color;
  switch (currgct) {
    case "UP":
      color = "yellow";
      break;
    case "DOWN":
      color = "red";
      break;
  };
  xmlcurrgct.send();;
</script>

I am not sure what I am missing.The variable can have 2 values UP or DOWN.

JSON:
{"text":{"currgct":"UP"}}

Can someone help me in finding where I am going wrong?


Solution

  • Try with this:

    var xmlcurrgct = new XMLHttpRequest();
    var urlcurrgct = "../json/currgct.json";
    xmlcurrgct.onreadystatechange = function () {
        if (xmlcurrgct.readyState == 4 && xmlcurrgct.status == 200) {
            console.log("xmlcurrgct.responseText", xmlcurrgct.responseText);
            var obj1 = JSON.parse(xmlcurrgct.responseText);
            console.log("obj1", obj1);
            document.getElementById("currgct").innerHTML = obj1.text.currgct;
    
            // You need to wait for the asynchronous response.
            var color;
            switch (obj1.text.currgct) {
                case "UP":
                    color = "yellow";
                    break;
                case "DOWN":
                    color = "red";
                    break;
            };
    
            document.getElementById("currgct").setAttribute("style", "color: " + color + ";");
        }
    }
    xmlcurrgct.open("GET", urlcurrgct, true);
    xmlcurrgct.send();