Tyrion Tyrion - 5 months ago 16
HTML Question

Javascript if else statement with redirecting to page doesn't work

I have this HTML page with javascript:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Login</title>
<script type="text/javascript">
window.onload = function () {
function websiteBeoordelen () {
var code = document.getElementById("code").value;
if (code == 101101) {
document.getElementById('button').onclick = function() {
location.href = "http://google.nl";
}
}
else {
document.write("The code is wrong, try again!");
}
}
while (code != 101101) {
document.getElementById('button').onclick = websiteBeoordelen;
}
};
</script>
</head>

<body>
<div id="wrap">

<table border="0">
<form method="post">
<label>Code:</label><input name="code" id="code" type="text" class="input"/>
<br /><br />
<label>&nbsp;</label><input name="submit" type="submit" id="button" value="Login" class="button" style="cursor:pointer"/>
</form>
</table>

</div>

</body>
</html>


I want to redirect the user to a page if he or she had the correct code. If the code is incorrect, I want to have it written underneath the button on the same page, but the user has to be able to try again.

I know this might be a very simple problem to solve, but I've just started working with Javascript so it will mean a great deal if you guys can help me out so I can understand Javascript better.

Answer

Its simple, change your code to this:

    window.onload = function () {
    function websiteBeoordelen () {
        var code = document.getElementById("code").value;
        if (code == 101101) {
            document.getElementById('button').onclick = function() {
                location.href = "http://google.nl";
            }
        }
        else {
            document.write("The code is wrong, try again!");
        }
      return false;   
    }
   document.getElementById('button').onclick = websiteBeoordelen;
};

Just removing the while loop would make it work.

Added return false to prevent page refresh.