JS - functions
guess the number
We will write a small function in Javascript(JS) which will process a (given) number. The goal of our little "game" will be to input a number (guess one) and the function will determine if the input number matches a number (which should be guessed).
The function will return if the we guessed right or if the guessed number is too low or to high.
The function called
guessNumber() takes the number from the form
Form1.
Form1 is the name of the form in the body. The input number is addressed with
parseFloat(document.Form1.txtNumber.value) where
txtNumber addresses the input field name (in the form
Form1). This data recieved is a string and with
parseFloat() the string will be transformed into a float so that we can use the compare-operator(to determine if the input number is our guessed one! This number is stored in the variable
Number
After that the function will determine if we found our number(or it is too high/low). Depending on the case - the value
output belonging to
Form1 will be written with the result (
document.Form1.output.value).
001
002
003
004
005
006
007
008
009
010
011
012
013
014
015
016
017
018
019
020
021
022
023
024
025
026
027
028
029
030
031
032
033
<html>
<head>
<script type = "text/javascript">
function guessNumber()
{
var Number = parseFloat(document.Form1.txtNumber.value);
if (Number < 100)
document.Form1.output.value = "the number is too small";
else if (Number > 100)
document.Form1.output.value = "the number is too big";
else
document.Form1.output.value = "guessed!";
}
</script>
</head>
<body>
<form method = "get" name = "Form1">
input number:
<input type = "text" name = "txtNumber"></input>
<input type = "button" value = "guess" onclick = "guessNumber()"></input>
<br>
<input type = "text" name = "output"></input>
</form>
</body>
</html>
The function itself will be called by an onClick-Event(pressed button):
onclick = "guessNumber()". We picked 100 for the number which should be guessed.
online-Demo:
guess the number