0

I have a json that is read with ajax in php. One of the variables is either true or false. I am having trouble getting it to work with an if statement.

   "batsman1": {
    "Name": "Anvesh *",
    "Runs": "0",
    "Balls": "0",
    "StrikeRate": "-",
    "currentlyOnStrike": true
  },
  "batsman2": {
    "Name": "Anuj ",
    "Runs": "3",
    "Balls": "2",
    "StrikeRate": "150.00",
    "currentlyOnStrike": false
  },

JS:

            var onstrike1 = data.batsman1.currentlyOnStrike;
            var onstrike2 = data.batsman2.currentlyOnStrike;
            if(onstrike1 == 'true'){
                document.getElementById("onstrike1").innerHTML = "*";
            }else{document.getElementById("onstrike1").innerHTML = onstrike1;}

            if(onstrike2 == 'true'){
                document.getElementById("onstrike2").innerHTML = "*";
            }else{document.getElementById("onstrike2").innerHTML = onstrike2;}

It is always showing false in this script. What am I not seeing?

David Morin
  • 485
  • 3
  • 5
  • 16

2 Answers2

2

JSON booleans will be translated to Javascript booleans, so you can simply just:

if(onstrike1 === true)
Collbrothers
  • 155
  • 1
  • 12
1

I think the prblem is that you're comparing onstrike1 with a string. So,

Do this

if(onstrike1)

Or

if(onstrike1 === true)

Instead of this

if(onstrike1 == 'true')

You're comparing onstrike1 value to a string while true/false is of Boolean type

Uzair Saiyed
  • 575
  • 1
  • 6
  • 16