I'm trying to generate a random number when the page loads, but it doesn't seem to work for some reason. The random number just keeps on being generated every time the user presses the submit button and not only once from the beginning of the page load.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title> How many fingers </title>
<script type="text/javascript" src="main.js"> </script>
</head>
<body>
<h1> Test your luck </h1>
<h2> How many fingers do I have?<h2>
<input type="text" id="myGuess">
<button id="button" onclick="check()"> submit </button>
</body>
</html>
My JavaScript:
function loadNumber(){
var myNumber = (Math.floor(Math.random()*10) +1);
}
//am not sure if the above function should generate the random number!
window.onload = loadNumber;
function check(){
var numberOfGuesses = (Math.floor(Math.random()*9)+1);
var guess = document.getElementById("myGuess").value;
var number = (Math.floor(Math.random()*10) +1);
if(guess==number){
alert("correct, it took you " + numberOfGuesses + " guesses to get it
right")
document.location.reload();
}else{
numberOfGuesses++;
alert("nope, try again!")
}
}
I am very confused by your code really. So I restructured it to bring myNumber and numberOfGuesses outside of the functions, in order to broaden the scope. On page load it generates the random number in loadNumber() which is in the root scope here. Then check can access that and incriment guesses.
var myNumber;
var numberOfGuesses = 0;
function loadNumber(){
myNumber = (Math.floor(Math.random()*10) +1);
}
function check(){
numberOfGuesses++;
var guess = document.getElementById("myGuess").value;
if(guess==myNumber){
alert("correct, it took you " + numberOfGuesses + " guesses to get it
right")
document.location.reload();
} else {
alert("nope, try again!")
}
}
window.onload = loadNumber;
On line 14 document.location.reload(); you are reloading the page and recalling the random number function, hence regenerating a new number.
The random number was changing, because you were generating a new random number every button click. Also the myNumber variable that you generate in loadNumber() was not available outside the function's scope and it was not used in the button's onClick function.
In the snippet below I transported the declaration of myNumber outside the function so that the both functions could access it and also constructed the guesses counter (with a starting value of 0)
var myNumber;
var numberOfGuesses = 0;
function loadNumber() {
myNumber = Math.floor(Math.random() * 10) + 1;
}
function check() {
numberOfGuesses++;
var guess = document.getElementById("myGuess").value;
if (guess == myNumber) {
alert("correct, it took you " + numberOfGuesses + " guesses to get it right");
document.location.reload();
} else {
alert("nope, try again!");
}
}
loadNumber();
<!DOCTYPE html>
<html>
<head>
<title>How many fingers</title>
<script type="text/javascript" src="main.js"> </script>
</head>
<body>
<h1>Test your luck</h1>
<h2>How many fingers do I have?<h2>
<input type="text" id="myGuess">
<button id="button" onclick="check()">submit</button>
</body>
</html>
var numberOfGuesses = (Math.floor(Math.random()*9)+1);
var guess = document.getElementById("myGuess").value;
var number = (Math.floor(Math.random()*10) +1);
function check() {
if(guess==number){
alert("correct, it took you " + numberOfGuesses + " guesses to get it right")
}else{
numberOfGuesses++;
alert("nope, try again!")
}
}
Put var myNumber = 0, numberOfGuesses = 0; outside both functions so it is a global variable that can be accessed in both functions.
Inside check() you can increment the number of guesses by putting numberOfGuesses++; and compare against the global variable myNumber instead of number.
Thank you all for the amazing support. Below is my final working code:
My Javascript:
var myNumber;
var numberOfGuesses = 1;
function loadNumber(){
myNumber = (Math.floor(Math.random()*10) +1);
}
window.onload = loadNumber;
function check(){
var guess = document.getElementById("myGuess").value;
if(guess==myNumber){
alert("correct, it took you " + numberOfGuesses + " guesses to get it
right")
document.location.reload();
} else {
numberOfGuesses++;
alert("nope, try again!")
}
}
My HTML:
<!DOCTYPE html>
<html>
<head>
<title> Guess Game </title>
<script type="text/javascript" src="main.js"> </script>
</head>
<body>
<h1> Test your luck </h1>
<h2> How many fingers Am I holding up?<h2>
<input type="text" id="myGuess">
<button id="button" onclick="check()"> submit </button>
</body>
</html>
Related
I need to figure out how to make a random number generator from 1-100 using HTML javascript. After finding the number from 1-100 I need to tell whether the number is odd or even. This is what I have so far:
<!DOCTYPE html>
<html>
<body>
<p>By clicking this button you will genarte a number from 1 to 100 </p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementById("demo")
x.innerHTML = Math.floor((Math.random() * 100) + 1);
if (a%==0)
system.out.println("Even Number");
else
system.out.println("Odd Number");
}
</script>
</body>
</html>
I think I have the random number generator right, but not the odd or even.
Please help.
You seem to have mixed up Java and JavaScript a little bit. JavaScript is what runs in browser, Java is a VM you download (and can sometimes run in browser, if you have the extension enabled/installed). system.out.println is Java. I went ahead and changed stuff out to make it entirely JavaScript.
function myFunction() {
var x = document.getElementById("demo"),
randomNum = Math.floor((Math.random() * 100) + 1);
x.innerHTML = randomNum
if (randomNum % 2 == 0) {
console.log("Even Number");
} else {
console.log("Odd Number");
}
}
<!DOCTYPE html>
<html>
<body>
<p>By clicking this button you will genarte a number from 1 to 100 </p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
You seem to be mixing java / javascript, to show you the code first:
<!DOCTYPE html>
<html>
<body>
<p>By clicking this button you will genarte a number from 1 to 100 </p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var ele = document.getElementById("demo");
var number = Math.floor((Math.random() * 100) + 1);
ele.innerHTML = number
if (number%2==0) {
alert("Even Number");
}
else {
alert("Odd Number");
}
}
</script>
</body>
</html>
There is no system.out.println in Javascript, you needed some more brackets and lastly to check for even check you missed a %2.
I have a problem with the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/main.css">
<title>The Ultimate Quiz Challenge</title>
</head>
<body>
<div class="container">
<h1>The Ultimate Quiz Challenge</h1>
<script>
document.write("<h3> " + "Welcome to the ultimate quizz challenge" +"</h3>");
document.write("<p> "+"Hi I will ask you five questions and then rank you" + "</p>");
var question1 ="<p>What is the capital of England</p>";
var firstanswer ="London";
var question2 = "<p>How many sides are there to a square</p>";
var secondanswer = 4;
var noofquestions = 2;
var count = 1
/*var temp = eval('question' +1); */
/*document.write(temp);*/
/* main loop asking questions */
while (count <= 2) {
var temp = eval('question' + count);
document.write(temp);
var answer = prompt("Please type your answer ");
count++;
}
</script>
</div>
</body>
</html>
When I load the file into a browser such a chrome or safari it does not execute as hoped.
In short the document.write commands do not come out onto the screen until the prompt window as asked for two inputs. I thought the first thing to be seen would be the Ultimate Quiz Challenge followed by the commands in the open script tag down to the bottom ?
You should use the onload event on your body, so your script executes once the html page is rendered. It should work with :
<body onload="displayText()">
displayText() being a function you define in your script :
var displayText = function () {
while (count <= 2) {
var temp = eval('question' + count);
document.write(temp);
var answer = prompt("Please type your answer ");
count++;
}
};
or something similar.
I have five jpg pictures and on a homepage i want to choose between these five pics by typing 1,2,3,4 or 5 and click OK and then i want that picture to show.
My code looks like this:
var inputElem, msgElem;
function init() {
msgElem = document.getElementById("message");
inputElem = [];
inputElem[1] = document.getElementById("input1");
inputElem[2] = document.getElementById("input2");
inputElem[3] = document.getElementById("input3");
document.getElementById("btn1").onclick = showFruit;
}
window.onload = init;
function showFruit() {
var nr, fruitUrl;
fruitUrl = (fruitImg.src = "pics/fruit" + nr + ".jpg");
nr = Number(input1.value);
fruitImg.src = "pics/fruit" + nr + ".jpg";
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
The problem is that I can't change the picture.I don't know whats missing, or how to make it choose between pic 1-5.
I have no privilege to write comments, so can't estimate what you actually want. But the resulting effect may be the thing you want.
But have look up below examples (live here). Enter a number then click button.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp">
<input type="submit" id="btn1" onclick="showFruit('inp')">
<script type="text/javascript">
makeImageFromNum = function (n) {
var nr = document.getElementById(n).value;
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
In below example (live here) just change the number - no need to click a button, there is no any actually :)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp" onchange="showFruit(this.value)">
<script type="text/javascript">
makeImageFromNum = function (nr) {
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
Note that you're always assinging the first image in this line of code (the last Iine if your code)
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
So, you'll always see image one
i found and edited this code from this website for practice but the code wont work with me. the goal of the code is to create a username and password on one page (which for now is limited to premade usernames and passwords) and send that array of information to another page where you can log in using the username and password from the other page. the code looks fine to me but i am an amateur and want to know what is wrong with it. thank you for your answer.
the code for where the username and password are defined is:
<!DOCTYPE html>
<html>
<head>
<title>
create account
</title>
<script>
sessionStorage.setItem("unArray", JSON.stringify("bob", "sam"));
sessionStorage.setItem("pwArray", JSON.stringify("lol", "jk"));
</script>
</head>
<body>
</body>
</html>
the code for taking the already created username and password from the above page and using that for a log in page is this:
<!DOCTYPE html>
<html>
<head>
<title>
log on page
</title>
<script type = "text/javascript">
var count = 2;
function validate() {
var un = document.getElementById("username").value;
var pw = document.getElementById("pword").value
var valid = false;
var unArray = JSON.parse(sessionStorage.getItem("unArray"));
var pwArray = JSON.parse(vsessionStorage.getItem("pwArray"));
for (var i=0; i <unArray.length; i++) {
if ((un == unArray[i]) && (pw == pwArray[i])) {
valid = true;
break;
}
}
if (valid) {
alert ("Login was successful");
window.location = "http://www.google.com";
return false;
}
var t = " tries";
if (count == 1) {t = " try"}
if (count >= 1) {
alert ("Invalid username and/or password. " +
"You have " + count + t + " left.");
document.myform.username.value = "";
document.myform.pword.value = "";
setTimeout("document.myform.username.focus()", 25);
setTimeout("document.myform.username.select()", 25);
count --;
}
else {
alert ("Still incorrect! You have no more tries left!");
document.myform.username.value = "No more tries allowed!";
document.myform.pword.value = "";
document.myform.username.disabled = true;
document.myform.pword.disabled = true;
return false;
}
}
</script>
<style>
p.log_on{
position: fixed;
top: 30px;
left: 20px;
}
</style>
</head>
<body>
<form name = "myform">
<p class="log_on">
ENTER USER NAME <input type="text" id="username"><br><br><br><br><br>
ENTER PASSWORD <input type="password" id="pword">
<input type="button" value="Check In" id="Submit" onclick="validate()">
</p>
</form>
</body>
</html>
The following two lines:
sessionStorage.setItem("unArray", JSON.stringify("bob", "sam"));
sessionStorage.setItem("pwArray", JSON.stringify("lol", "jk"));
are not using the JSON.stringify function correctly.
They should be:
sessionStorage.setItem("unArray", JSON.stringify(["bob", "sam"]));
sessionStorage.setItem("pwArray", JSON.stringify(["lol", "jk"]));
See the following link for reference: Mozilla Developer Network.
Per the documentation, the JSON.stringify parameters are defined as the following:
Syntax
JSON.stringify(value[, replacer [, space]])
Parameters
value - The value to convert to a JSON string.
replacer (Optional) - If a function, transforms values and properties encountered while stringifying; if an array, specifies the set of properties included in objects in the final string.
A detailed description of the replacer function is provided in the JavaScript guide article Using native JSON.
space (Optional) - Causes the resulting string to be pretty-printed.
I have been trying to make all my Javascript Page code from JSBin to work automatically upon the clicking of a button. Problems include not being able to run the code because it says I have multiple variables in my script that do not work together and not being able to put it all in HTML because console.log doesn't work. I tried a couple different ideas, but sadly, I am unable to do it correctly.
My Code Is:
var name = prompt('So what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
var name = prompt('Than what is your name?');
var confirmNamed = confirm('So your name is ' + UCFL(name) + '?');
}
if (confirmNamed === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmNamed === false) {
var name = prompt('Than what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
alert('Oh, guess what? I do not even fucking care what your name is anymore. Lets just
start..');
var start = confirm('Are you ready?');
}
}
if (start === true) {
var x = console.log(Math.floor(Math.random() * 5));
if (x === 1) {
alert('You are an dwarf in a time of great disease.');
alert('');
}
}
And this is what I want you to fix:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="" />
</form>
</body>
</html>
I've created an entry on JSBin suggesting many improvements to what you have now:
http://jsbin.com/epurul/3/edit
Visit the entry to test the code yourself. Here is the content, for convenience:
HTML:
<body>
<button onclick="playGame()">Play Game</button>
</body>
And JavaScript:
// Expose playGame as a top-level function so that it can be accessed in the
// onclick handler for the 'Play Game' button in your HTML.
window.playGame = function() {
// I would generally recommend defining your functions before you use them.
// (This is just a matter of taste, though.)
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
// Rather than capitalize name everywhere it is used, just do it once
// and then use the result everywhere else.
function getName(message) {
return UCFL(prompt(message));
}
var name = getName('So what is your name?');
// Don't repeat yourself:
// If you're writing the same code in multiple places, try consolidating it
// into one place.
var nameAttempts = 0;
while (!confirm('So your name is ' + name + '?') && ++nameAttempts < 3) {
// Don't use 'var' again as your name variable is already declared.
name = getName('Then what is your name?');
}
if (nameAttempts < 3) {
alert('Good. Lets start the roleplay, Sir ' + name + '.');
} else {
alert("Oh, guess what? I do not even fucking care what your name is anymore. Let's just start...");
}
};
Put your code in a function, for example:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function runGame() {
// put your js code here
}
</script>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="runGame();" />
</form>
</body>
</html>
It would also be a good idea to copy your js code to another file and import that using a script tag, for instance:
<script src="path/to/file.js"></script>