Why can't I access an ID value inside an IF statement?

I would like to make script which allows only devices with equal IP address as code but I can't make it with if statement. When I write x.id inside the statement it doesn't work... Ideas?

<html>
<script type="text/javascript">
    window.onload = function () {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "https://api.ipify.org?format=jsonp&callback=DisplayIP";
        document.getElementsByTagName("head")[0].appendChild(script);
    };
    function DisplayIP(response) {
        var x = document.getElementById("ipaddress").innerHTML = response.ip;
    }
</script>
</head>
<p id=ipaddress></p>
<form name="login">
<input type="button" onclick="check()" value="check ip">
</form>

<script language="javascript">
function check()
{
 if(x.id == "22.333.444.555")
  {
    window.open('ipadressok.html')
  }
 else
 {
   alert("ip adress unknown")
  }
}
</script>
</html>

1 answer

  • answered 2018-10-09 16:46 inoabrian

    You can add the getIPAddress function.

    When you fire the check function you can assign the value to x.

    This is needed because x is not a global variable and will not be defined if referenced before being declared in the scope of the check function.

    <html>
    <script type="text/javascript">
    window.onload = function () {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.src = "https://api.ipify.org?format=jsonp&callback=DisplayIP";
        document.getElementsByTagName("head")[0].appendChild(script);
    };
    
    function DisplayIP(response) {
        document.getElementById("ipaddress").innerHTML = response.ip;
    }
    
    // Add this function here to retrieve the value of the ipAddress element.
    function getIPAddress() {
        return document.getElementById("ipaddress").innerHTML;
    }
    
    function check() {
        // Declaring and assigning x in here
        var x = getIPAddress();
        
        if (x == "22.333.444.555") {
            window.open('ipadressok.html')
        } else {
            alert("ip adress unknown")
        }
    }
    </script>
    </head>
    <body>
    <p id=ipaddress></p>
    <form name="login">
        <input type="button" onclick="check()" value="check ip">
    </form>
    </body> 
    </html>