Proper use of comparison operators

I am new to HTML and have used Eclipse for Java before. Below I try to have the user enter a number (0-5), and try the computer and guess it.

I looked through it and it seems that it sounds, the only thing I have never done is to put an element equal to another element at the end of the loop.

Also the first time using non-instructions ( is it !== or !=?) in HTML/JavaScript.

HTML

<p>How many fingers am I holding up?</p>
<input id="fingers"></input>
<div>
    <button id="button">Input fingers</button>
</div>

Javascript

var i = 0;
var cg = 0;

document.getElementById("button").onclick = function() {
    while (i !== fingers) {
        cg = Math.random();
        cg = cg * 6;
        cg = Math.floor(cg);

        if (document.getElementById("cg").value !== fingers) {
            alert("Wrong we found " + cg);
            i = cg;
        } else {
            alert("The number of fingers is " + cg);
            i = cg;
        }
    }
}

I myself study this for future use, I hope you can help! Thank.

+4
source share
3 answers

You do not have an html element with id cg, so this line fails document.getElementById("cg").value. However, you have fingershtml as a text box.

, (! == or! =?) HTML/JavaScript.

js , , != . ,

5 != '4' // true
5 != '5' // false

5 !== '4' // true
5 !== '5' // true

5 !== 5 // false
5 !== 4 // true

, , , :

<script type="text/javascript">

var cg;
var fingers = document.getElementById("fingers");

document.getElementById("button").onclick=function() {
  cg = Math.floor(Math.random()  * 6);
  if (fingers.value != cg) {
    alert ("Wrong, it was: " + cg);
  }
  else {
    alert ("Right !!");
  }
};
</script>
+6
<script type="text/javascript">
    var i = 0;
    var cg = 0;

    document.getElementById("button").onclick = function() {
        while (i !== fingers.value) {
            cg = Math.random();
            cg = cg * 6;
            cg = Math.floor(cg);

            if (parseInt(cg) !== parseInt(fingers.value)) {
                alert("Wrong we found " + cg);
                i = cg;
            } else {
                alert("The number of fingers is " + cg);
                break;
            }
        }
    }
</script>
+4

Check your identifiers! Your JS is trying to find an element that is identified as "cg", but the only identifiers I see are 'button' and 'fingers'.

+2
source

All Articles