In: Computer Science
Assume user will enter letters or numbers that are out of range. When user inputs invalid values, show an alert message and ask user to enter a valid value again. Validate first and then proceed with the program. isNaN() method may be useful. Must validate user input.
1. Suggested Filename: fortune.html &
fortune.js
Write a program that simulates a fortune cookie. The program should
display one of five unique fortunes, depending on user input. The
user must enter a number between 1 and 5 only.
2. Suggested Filename: number.html & number.js
Implement “Guess my Number” game. Here is a link to the game
https://www.funbrain.com/games/guess-the-number
Implement the basic game where you tell the user if their guess is higher or lower than the random number. You are welcome to add other constraints such as the number of chances a user gets.
Generating a random number between 1 and 100 using the random method:
var num = Math.floor((Math.random() * 100) + 1);
Remember, any user input is a string- you must convert it to an integer or a float before comparing it to other numbers.
1) fortune.html
<!DOCTYPE html>
<html>
<head>
<title>Fortune Cookie</title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<script src="fortune.js">
</script>
</head>
<body>
<h2>Fortune Cookie</h2>
<form onSubmit="formvalidation();" id="fortuneform">
Enter any number from 1 to 5
<input type="text" name="fortuneNum">
<input type="submit" value="Submit">
</form>
</body>
</html>
fortune.js
function formvalidation()
{
var inpval =
parseInt(document.getElementById("fortuneform").elements.namedItem("fortuneNum").value);
if(!isNaN(inpval) && inpval>=1 &&
inpval<=5)
{
var inpval
=parseInt(document.getElementById("fortuneform").elements.namedItem("fortuneNum").value);
switch(inpval)
{
case 1 : alert("Will have lucky day");
break;
case 2 : alert("Bonus salary");
break;
case 3 : alert("Promotion in job ");
break;
case 4 : alert("Meet old friend");
break;
case 5 : alert("New love life");
break;
}
}
else
{
alert("Invalid Input! Please enter again")
}
}
2). number.html
<!DOCTYPE html>
<html>
<head>
<title>Guess Number</title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<script src="number.js">
</script>
</head>
<body>
<h2>Guess number</h2>
<form onSubmit="guessnum();" id="guessnumform">
Enter any number from 1 to 100
<input type="text" name="guessnum">
<input type="submit" value="Submit">
</form>
</body>
</html>
number.js
function guessnum()
{
var inpval =
parseInt(document.getElementById("guessnumform").elements.namedItem("guessnum").value);
var lucknum = Math.floor(Math.random() *100) + 1;
if(inpval>lucknum)
{
alert("your number greater then lucky number");
}
else if(inpval<lucknum)
{
alert("your number less then lucky number");
}
else
{
alert("your number is equal to luc number");
}
}