Random num Generator/ odd and even - javascript

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.

Related

I want to be able to change a variable to true with the click of a button

So i want to make my button so it changes to true in the Script part. This is so a random number will appear in the p element
<!doctype html>
<html>
<button>
random number
</button>
<p id="randomnumber">
</p>
</html>
<script>
if (document.getElementById('button').clicked == true)
{
document.getElementById("randomnumber").innerHTML = (Math.floor(Math.random()*21)+2);
}
</script>
Edit:I was also wondering how to assign the random number to a variable so i can use the random number as a variable.
Hi Jeremy try this code please.
<!doctype html>
<html>
<button id="button">
random number
</button>
<p id="randomnumber">
</p>
</html>
<script>
document.getElementById('button').addEventListener('click', function() {
document.getElementById("randomnumber").innerHTML = (Math.floor(Math.random() * 21) + 2);
})
</script>
You're probably looking for element.addEventListener()
document.querySelector('#button').addEventListener('click', () =>
document.querySelector("#random-number").textContent = Math.floor(Math.random() * 21) + 2);
<button id="button">random number</button>
<p id="random-number"></p>
Some tips:
use dashes in element ID's
format your code cleanly
use document.querySelector() instead of document.getEementById()
use element.textContent instead of element.innerHTML

Javascript if statement issue: No display in the webpage

I have a VERY BASIC knowledge of javascript and I was looking forward to learn some conditional statement in javascript. So I went on and entered this code in a HTML file called "index.html":
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
And the result that came was completely normal. A title called "Sample Webpage" appeared.
But the next code what I entered created problems in the result,
var myNumber = window.prompt("Enter number: ");
parseFloat(myNumber);
document.write(myNumber);
The result comes as expected.
if (myNumber > 15) {
document.write(<p>Good! You've passed! </p>);
}
else {
document.write(<p>You failed! Try again next time.</p>);
}
But when I add this if statement which gives an output based on the user's input, I get a blank page. I don't understand what is the reason for this. Are there any problems in the syntax?
It also seems to me that it doesn't execute the first part of the code I've written, it completely wants all of the code. I feel this is normal but doesn't it have to actually execute the "document.write" code?
Way I see it, you need to quote your strings in document.write(string).
like this:
if (myNumber > 15) {
document.write("<p>Good! You've passed! </p>");
}
else {
document.write("<p>You failed! Try again next time.</p>");
}
I hope it is useful for you. Thank you.
document.write takes a string as argument. You pass it HTML.
Just change
document.write(<p>Good! You've passed! </p>);
to
document.write('<p>Good! You've passed! </p>');
to make it work. A better approach is to add
<p id="message"></p>
to the page and where you have
document.write('<p>Good! You've passed! </p>');
you can use
document.getElementById('message').textContent='Good! You've passed!';
document.getElementById("myButton").addEventListener('click', function() { // when clicked
let myNumber = window.prompt("Enter number: ");
myNumber = parseFloat(myNumber); // convert to number from string
document.getElementById('number').textContent = myNumber;
const msg = document.getElementById('number'); // output container
if (myNumber > 15) {
msg.textContent = 'Good! You\'ve passed!' // escaping the quote
}
else {
msg.textContent = 'You failed! Try again next time.';
}
});
// above can be written using a so called ternary:
// msg.textContent = myNumber > 15 ? 'Good! You\'ve passed!' : 'You failed! Try again next time.'
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<p id="number"></p>
<p id="message"></p>
<button type="button" id="myButton">Did you pass?</button>
<script src="script.js"></script>
</body>
</html>

How to generate a random number on page load?

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>

How do you create a button that changes the image to the next image in an image array

I have an assignment that requires me to code a website using HTML and JavaScript. The Website is just a very basic website (I'm a Computer Science Student just starting HTML) about the planet in the solar system.
The website includes two buttons, as you'll see in the below code, that change the text on the screen to the next planet in the solar system however sometimes when the buttons are clicked this doesn't occur, instead the text changes to the incorrect planet or simply states "undefined" until the button is clicked a few more times when the website will continue to work correctly.
Here's my code:
<html>
<body bgcolor="cyan">
<h1>The Solar System</h1>
<script>
var planets= ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"];
var endofplanets=planets.length;
var i =0;
function nextplanet(){
if (i<endofplanets){
document.getElementById('p1').innerHTML=planets[i];
i++;
}
}
</script>
<script>
function previousplanet(){
if (i>-1){
document.getElementById('p1').innerHTML=planets[i];
i--;
}
}
</script>
<p id="p1">---</p>
<button type="button" onclick=nextplanet()>Next Planet</button>
<button type="button" onclick=previousplanet()>Previous Planet</button>
</body>
</html>
Any help with this would be much appreciated
Try this.. simple solution
<html>
<body bgcolor="cyan">
<h1>The Solar System</h1>
<script>
var planets= ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"];
var endofplanets=planets.length;
var i = -1;
function nextplanet()
{
i=i+1;
if(i==endofplanets){
i=0;
}
document.getElementById('p1').innerHTML=planets[i];
}
function previousplanet(){
i=i-1;
if(i<0){
i=endofplanets-1;}
document.getElementById('p1').innerHTML=planets[i];
}
</script>
<p id="p1">---</p>
<button type="button" onclick="nextplanet()">Next Planet</button>
<button type="button" onclick="previousplanet()">Previous Planet</button>
</body>
</html>
check this:- you need to add else condition in next button and reset i value to 0, this is fiddle https://jsfiddle.net/3bsyypL9/2/
<html>
<body bgcolor="cyan">
<h1>The Solar System</h1>
<script>
var planets= ["Mercury","Venus","Earth","Mars","Jupiter","Saturn","Uranus","Neptune"];
var endofplanets=planets.length;
var i =0;
function nextplanet(){
if (i<endofplanets){
document.getElementById('p1').innerHTML=planets[i];
i++;
}
else
{
i = 0;
document.getElementById('p1').innerHTML=planets[i];
i++;
}
}
</script>
<script>
function previousplanet(){
if (i>0){
i--;
document.getElementById('p1').innerHTML=planets[i];
}
}
</script>
<p id="p1">---</p>
<button type="button" onclick="nextplanet()">Next Planet</button>
<button type="button" onclick="previousplanet()">Previous Planet</button>
</body>
</html>
The answer of DHRUV GUPTA contain an error, when i equals 7, if you do nextplanet() then i is increased by one. So if you trigger the function previousplanet(), i is equal to 8 and you get an undefined result.
The simplest way to avoid this error is to not increase i everytime.
Check this :
http://codepen.io/anon/pen/EZbBVX
NO LOOP VERSION
i = -1; //To be sure that the first planet will be Mercury
function nextplanet(){
if (i<endofplanets){
i = Math.min(i+1,endofplanets-1); //Take the minimum between i+1 and last indice of your array (7), so i will ever be lower of equal to the max indice of your array
document.getElementById('p1').innerHTML=planets[i];
}
}
function previousplanet(){
if (i>-1){
i = Math.max(i-1,0); //The same, i will be ever greater or equal to 0, which is the lower indice of your array ;)
document.getElementById('p1').innerHTML=planets[i];
}
}
LOOP VERSION
i = 0;
function nextplanet(){
document.getElementById('p1').innerHTML=planets[i];
i = (i+1) % endofplanets; //With a modulo, your indice is always between 0 and endofplanets-1, google modulo if you don't know this operator ;)
}
function previousplanet(){
document.getElementById('p1').innerHTML=planets[i];
i = (i-1) % endofplanets;
}

Javascript - multiplying a value with itself

I want to write a script that multiplies any number in a text field with itself by the push of a button and gives the result as an alert.
I'm completely new to Javascript (and have to write my first exam later today).
The syntax is killing me, sometimes so similar to Java, but than again not.
Here's what I came up with so far:
<!DOCTYPE html>
<html>
<head>
<script>
function myMultiply()
{
var x= $('#num1').val();
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1">
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
You'll want to make sure you parse the input value as it will be a string when you query for it. To operate on it using multiplication, you need a number. You'll usually want to pass 10 as the second radix parameter as there are different implementations of parseInt
function myMultiply() {
var x = parseInt($('#num1').val(), 10);
var y = x*x;
alert(x + " times " + x + " equals " + y);
return false;
}
You cant multiply string it will be concatenated, parse value to int using parseInt first
parseInt
function myMultiply()
{
var x= parseInt($('#num1').val(), 10);
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
try replacing var y=x*x; with var y=Number(x)*Number(x);
Along with other answers indicating you should parseInt it should be noted that you aren't currently including jQuery (which gives you access to the $(".element") notation).
jQuery is a very common javascript library that saves a lot of time for very common Javascript tasks (selectors, events etc). You'll see the $() notation in many tutorials and to use it you need to include jQuery.
This will work:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function myMultiply()
{
var x= parseInt( $('#num1').val(), 10 );
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1" />
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>
Your code is fine. You are simply missing the jquery include.
Add <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> right above your other script and everything works unchanged.
Javascript will parse strings and convert them to numbers automatically when it sees that you are trying to multiply. "4" * "2" is 8, not "44" or "42" or any other magical combination. You have a syntax error by referring to $ without actually including jQuery as a required script, so the function ends up being undefined.
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function myMultiply()
{
var x= $('#num1').val();
var y= x*x;
alert(x+" times "+x+" equals "+y);
return false;
}
</script>
</head>
<body>
<input type="text" id="num1">
<button onclick="myMultiply()">Try it</button>
<p>By clicking the button above, the value in the text field will be multiplied with itself.</p>
</body>
</html>

Categories