I am new to HTML and have used Eclipse for Java before. Below I am trying to have the user input a number (0-5) and have the computer try and guess it.
I have looked this over and it seems sound, the only thing that I have never done is put an item equal to another item at the end of the loop.
Also first time using not statements ( 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 am independently learning this for future use, I hope you can help! Thanks.
You don't have html element with id cg
, so this line fails document.getElementById("cg").value
. However you have fingers
as an html textbox.
Also first time using not statements (is it !== or !=?) in HTML/JavaScript.
In js, both are valid but they differ in functionality, !=
has an overhead of conversion. For eg
5 != '4' // true
5 != '5' // false
5 !== '4' // true
5 !== '5' // true
5 !== 5 // false
5 !== 4 // true
I tried to rectify your code and I ended up with this, hope it helps:
<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>
<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>
Check your IDs! Your JS is trying to find an element that is identified as 'cg', but the only IDs I see are 'button' and 'fingers'.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.