JavaScript OnClick Method - javascript

I was having trouble with the OnClick method I was learning while creating a game. Every time I enter the value and click the button, it is stuck in a loop, I tried document.write and it works using that, but than it opens a new page instead of showing up on screen.
I am new to the programming community, so any help would be nice.
<body>
<p>Enter an integer between 1-100 here:
<input id="number" type="text" />
</p>
<p>
<button onclick="onclickFunction()" type="button">Enter</button>
</p>
<p id="result"></p>
<script type="text/javascript">
function onclickFunction() {
var a = Math.random();
var b = a * 100;
var c = Math.ceil(b);
var intNumber;
var count = 0;
var bool = false;
do {
do {
intNumber = document.getElementById("number").value;
}
while (intNumber > 100 || intNumber < 0);
if (intNumber > c) {
document.getElementById("result").innerHTML = "Too High " + "</br>";
bool = false
} else if (intNumber < c) {
document.getElementById("result").innerHTML = "Too Low " + "</br>";
bool = false
} else if (intNumber == c) {
document.getElementById("result").innerHTML = "You Win!" + "<br>" + " It took you " + count + " tries";
bool = true
}
count = count + 1
} while (bool !== true);
document.getElementById("result").innerHTML = "Win!";
}
</script>
</body>
Updated:
<script type="text/javascript">
// Declare all your functions first
// These functions expect no parameters and return values.
function onclickFunction()
{
var a = Math.random();
var b = a * 100;
var c = Math.floor(b);
// Input from text box.
var randomNumber = document.getElementById("number").value;
// Output to paragraph.
if (randomNumber < c && randomNumber != c)
{
document.getElementById("result").innerHTML = "Too Low " + "</br>";
}
else if (randomNumber > c && randomNumber != c )
{
document.getElementById("result").innerHTML = "Too High" + "</br>";
}
else if (randomNumber == c)
{
document.getElementById("result").innerHTML = "Win!";
}
// Clear text box for further input.
document.getElementById("name").value = "";
}
</script>
<p>Enter an integer between 1-100 here: <input id="number" type="text" /></p>
<p><button onclick="onclickFunction()" type="button">Enter</button></p>
<p id="result"></p>
</body>

First of all, it is always useful to create a fiddle.
That way people who are reading your question can run your code immediately.
Let's break down the code
var a = Math.random();
var b = a * 100;
var c = Math.ceil(b);
This can be done in a single line, to save variables.
do
{
intNumber = document.getElementById("number").value;
}
while (intNumber > 100 || intNumber < 0);
I'm not a big fan of using do/while loops this way, although it can come handy when you want to run the do code at least once, like now.
This loop keeps running when the number is bigger than 100, or smaller than 0. So if I pick an incorrect number that means my browser crashes.
if (intNumber>c){
document.getElementById("result").innerHTML = "Too High " + "</br>";
bool = false
}else if (intNumber<c){
document.getElementById("result").innerHTML = "Too Low " + "</br>";
bool = false
}else if (intNumber == c){
document.getElementById("result").innerHTML = "You Win!" + "<br>" + " It took you " + count + " tries";
bool = true
}
First you are checking if the guess is bigger than the answer, than if it's smaller. That means that the last check if it's equal is unnecessary, since that is the only option left. You can just use an else here.
Also try to be consistent with your spacing and where you place your curly brackets.
do{
//Stuff
}
and
do
{
//Stuff
}
Are both valid ways to use brackets, but stick to one style or your code will get too confusing.
count = count + 1
A small oversight here is that the count starts at 0. So when you guess the number in a single try, it will say you have done it in 0 tries.
while (bool !== true);
document.getElementById("result").innerHTML = "Win!";
}
All the previous code will be done until bool becomes true. The problem here is that if I entered a wrong number (or an invalid number). The program will keep running the if statement which requires a lot of computer power since it never stops. It is impossible to change your guess and the page crashes, because the browser is stuck in the while loop.
The simplest solution for this is to calculate if the new guess was correct when the player inputs a new number. So when onClickFunction is called again.
That way you never have to use a while loop. Although you have to calculate the random number somewhere else.
I hope that helped, if you have any question let me know!

Related

Not sure why this JavaScript function is not working

I am writing JavaScript / HTML for a project for one of my classes. I'm not sure why the JavaScript function won't execute. The first return ("result") works no problem but for some reason my program wont work for ("result2"). I pasted the function down below:
function multiplyBy(){
var x = document.getElementById("text").value;
var y = document.getElementById("text2").value;
var z = x * y;
var a = 52 * z;
var b = paraseFloat(a);
if (b > 20000) {
output = "The Salary is too little."
}
if else (b < 20000; b > 25000) {
output = "The Salary is almost enough. Let's negotiate."
}
else {
output = "This is a great salary for me."
}
return document.getElementById("result").innerHTML = "The Salary is: " + b;
return document.getElementById("result2").innerHTML = output
}
You have few issues in the code
paraseFloat is a miss type it should be parseFloat
if else (b < 20000; b > 25000) {
if else should be else if
if you want to have a range in your check you need to add logical operators like && ||
and the you need to review the logic for checking the salary i am not sure but i have changed something that "has" some sense
you can check in here
function multiplyBy() {
var x = document.getElementById("text").value;
var y = document.getElementById("text2").value;
var z = x * y;
var a = 52 * z;
var b = parseFloat(a);
if (b < 20000) {
output = "The Salary is too little.";
} else if (b >= 20000 && b < 25000) {
output = "The Salary is almost enough. Let's negotiate.";
} else {
output = "This is a great salary for me.";
}
document.getElementById("result").innerHTML = "The Salary is: " + b;
document.getElementById("result2").innerHTML = output;
}
multiplyBy();
<input type='text' name='text' id='text' value=10 />
<input type='text' name='text2' id='text2' value=10 />
<div id='result'></div>
<div id='result2'></div>
I have found couple of issues in your code but you were almost there. Let me summarize in few steps where it was wrong:
In your code if else was presented. Using else if works other way around, read further here.
Logical AND operator for defining between values for salary works differently, here you can find details. b < 20000; b > 25000 is just wrongly defined, I have corrected to have b >= 20000 && b < 25000. Solution uses && and changed a bit the condition.
In parsing to float case there was a typo in your function call, should have parseFloat instead of paraseFloat. Read further here.
Just changed from b < 20000 to b > 20000 which makes more sense in terms of text result.
And lastly, in your function there are 2 return statements, even if there is no need at all in that code. The function manipulates the DOM then it will automatically return undefined. Please find here the documentation for more details which states:
A function without a return statement will return a default value. ... For all other functions, the default return value is undefined.
And finally here is a working solution:
function multiplyBy() {
const x = document.getElementById("text").value;
const y = document.getElementById("text2").value;
const z = x * y;
const a = 52 * z;
const b = parseFloat(a);
if (b < 20000) {
output = "The Salary is too little.";
} else if (b >= 20000 && b < 25000) {
output = "The Salary is almost enough. Let's negotiate.";
} else {
output = "This is a great salary for me.";
}
document.getElementById("result").innerHTML = "The Salary is: " + b;
document.getElementById("result2").innerHTML = output;
}
<input id="text" />
<input id="text2" />
<div id="result"></div>
<div id="result2"></div>
<button onclick="multiplyBy()">Calculate</button>
Additionally it is worth to read further about when to use const, let and var.
Hope this helps!

JS recognizes that var is String

I think the JS thought that var num was a String, but I want var num as a number! The problem says 'num' is not defined.
var num = document.getElementById('number').value;
var i = Math.floor(Math.random(0,num));
var c = document.getElementById('chance').value;
function clicked(){
var j = document.getElementById('game').value;
if (i > j){
document.getElementById('demo').innerHTML = "Bigger!";
c -= 1;
document.getElementById('re').innerHTML = "You have " + c + " more chances!";
} else if(num < j){
document.getElementById('demo').innerHTML = "The value is bigger than " + num + "!";
document.getElementById('re').innerHTML = " "
} else if (i < j){
document.getElementById('demo').innerHTML = "Smaller!";
c -= 1;
document.getElementById('re').innerHTML = "You have " + c + " more chances";
} else if (i == j){
document.getElementById('demo').innerHTML = "Correct!";
c = 14;
document.getElementById('re').innerHTML = " ";
i = Math.floor(Math.random()*num);
}
if (c == 0){
document.getElementById('demo').innerHTML = "Try again! The secret number was " + num;
c = 14;
document.getElementById('re').innerHTML = " ";
i = Math.floor(Math.random()*101);
}
}
<p>
You should guess a number between 0 ~ <input type="number" id="number"> under this text. You have total <input type="number" id="chance"> chances. Good luck!<br><br>
<input type="number" id="game"> <input type="submit" onclick="clicked()" value="GUESSED">
<p id="demo"></p>
<p id="re"></p>
</p>
I want an ID 'number' be var num, the random number between 0 and num:
which will be the var I, and an ID 'chance' be var c, the number of chances be the c. I hope you know what I mean, because I described precisely as I can. By the way, I am coding a number guessing game HTML and I am a coding nooooob. If you are nice, please help me out. Thank You.
See doc : https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/
var num1 = parseInt(num, 10);
The parseInt() method converts a string into an integer (a whole number).
It accepts two arguments. The first argument is the string to convert. The second argument is called the radix. This is the base number used in mathematical systems. For our use, it should always be 10.
The Number() method converts a string to a number.
Sometimes it’s an integer. Other times it’s a point number. And if you pass in a string with random text in it, you’ll get NaN, an acronym for “Not a Number.”
As a result of this inconsistency, it’s a less safe choice than parseInt() and parseFloat(). If you know the format of the number you’d like, use those instead. If you want the string to fail with NaN if it has other characters in it, Number() may actually be a better choice.
var num = document.getElementById('number').value always returns a string value. You can cast the value using https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number
num = Number(num);

JavaScript says 10 is lower then 9

I'm trying to learn JavaScript and when I started the MDN Tutorial, I tried to do the first exercise alone, which worked okay so far. But there is one really weird situation.
The Game generates a Random number from 1 - 100 and the User has 10 guesses to find out that number.
I simplified the game to 1 - 10 for this purpose.
When the random number is a 9 and i guess 10, the code says my input was too low. I don't understand why that is. In every other situation, it works exactly as expected.
For debugging reasons, the random number will be shown in the dialog after the first guess.
This is my code:
var number = 0;
var turns = 0;
var guess = 0;
var won = false;
playGame();
function playGame() {
won = false;
number = (Math.random() * 10).toFixed(0);
guess = prompt("Guess a number from 1 to 10");
turns = 0;
while(turns < 10) {
console.log(number + " " + guess);
if(guess < number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was to low! Guess again:");
won = false;
} else if(guess > number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was to high! Guess again:");
won = false;
} else if(guess === number) {
alert("You got it!");
won = true;
break;
}
}
if(confirm("Wanna play again?")){
playGame()
} else {
alert("kkbye!");
}
}
Thanks in advance. If you see something in my code you'd like to comment, I'd love to hear feedback and become better, even if it isn't directly related to this ;)
The problem is, that you are working with Strings, if you compare two strings with < it will only compare as many characters as it has to until it finds a character that is smaller (smaller being it's Integer representation) than another:
console.log("10" < "9");
Here it will only compare "1" to "9", meaning char code 49 to char code 57.
49 is less than 57, meaning the whole expression is true. You can learn more about the ASCII char codes here.
You should use Numbers instead:
console.log(Number("10") < Number("9"));
You are only dealing with Strings, since both prompt() and Number.toFixed() return Strings. If you encapsulate those in Number() calls your game works:
var number = 0;
var turns = 0;
var guess = 0;
var won = false;
playGame();
function playGame() {
won = false;
number = Number((Math.random() * 10).toFixed(0));
guess = Number(prompt("Guess a number from 1 to 10"));
turns = 0;
while(turns < 10) {
console.log(number + " " + guess);
if(guess < number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was too low! Guess again:");
won = false;
} else if(guess > number) {
turns++;
guess = prompt("Number is " + number + ".\n\nYou guessed " + turns + " Times already.\n\nYour guess was too high! Guess again:");
won = false;
} else if(guess === number) {
alert("You got it!");
won = true;
break;
}
}
if(confirm("Wanna play again?")){
playGame()
} else {
alert("kkbye!");
}
}
The Javascript Prompt returns a string. In fact, input text box always returns string. So when you enter 10 it returns "10" and toFixed() will also return string.
So you need to correct two lines from your code
number = parseInt((Math.random() * 10).toFixed(0));
guess = prompt("Guess a number from 1 to 10");
guess = parseInt(guess);
Also you need to check for NAN condition to be on safer side.

Beginner - document.write in while loop

I'm trying to make a program where the user guesses a number from 1 to 100. You get 10 guesses and, the program should tell the user if his/hers guess is too high or too low along the way, however the program does not write on the document until all 10 guesses are used. How can I get around this?
Here is my code:
var a = Math.random();
var b = a * (101 - 1) + 1;
var c = Math.floor(b);
document.write(b + "<br>");
document.write(c + "<br>");
var d = 1;
while (gjett != c && d <= 10) {
var gjett = Number(prompt("Gjett på et tall fra 0 til 100"));
if (gjett < c) {
document.write("Tallet er høyere enn " + gjett + ".<br>");
}
if (gjett > c) {
document.write("Tallet er lavere enn " + gjett + ".<br>");
}
d = d + 1;
}
Pro-tip: don't use document.write.
Now, the reason you aren't seeing anything is, basically, the browser is either in JavaScript mode or rendering mode. As long as some JavaScript is running, the DOM is not going to be rendered. That way if you make multiple changes to the DOM, the browser doesn't waste resources on rendering all of the little changes in between.
A better way of handling this would be with a button and some kind of input.
// Wait for the user to click on the button
document.querySelector('button').addEventListener('click', function() {
// Get the value the user put in
var inputEl = document.querySelector('input');
// Make sure it's an integer
var value = parseInt(inputEl.value);
// Get the output element
var outputEl = document.getElementById('output');
// Tell the user what they guessed
outputEl.innerHTML = 'You guessed ' + value;
});
<input type="text" />
<button>Try</button>
<br />
<p id="output"></p>
You can figure out the actual logic of the guessing game yourself ;)
As others have suggested, you should avoid using document.write() in real-world applications, as there are more effective ways of adding elements to a page.
To answer your question: you don't see the page update while you're repeatedly submitting your guesses because the browser is still evaluating your while() loop, and deferring the re-rendering of the visible page until the while loop terminates.
The most direct way to achieve what you're asking, without changing much of your code, would be to substitute your while loop with an interval, such that your code executes asynchronously and doesn't block the browser from updating the rendered page. (Because of its blocking nature, confirm() (like other methods like alert()) is probably not the best choice for this interaction.)
var a = Math.random();
var b = a * (101 - 1) + 1;
var c = Math.floor(b);
document.write(b + "<br>");
document.write(c + "<br>");
var d = 1;
var interval = setInterval(function() {
if (gjett != c && d <= 10) {
var gjett = Number(prompt("Gjett på et tall fra 0 til 100"));
if (gjett < c) {
document.write("Tallet er høyere enn " + gjett + ".<br>");
}
if (gjett > c) {
document.write("Tallet er lavere enn " + gjett + ".<br>");
}
} else {
clearInterval(interval);
}
}, 0);

Printing the next 10 even and odd numbers ( java-script)

1) If I enter an even number, I want next 10 even numbers to be printed. If I enter an odd number, I want next 10 odd numbers to be printed.
2)If I enter an even number, I want previous 5 even numbers to be printed. If I enter an odd number, I want previous 5 odd numbers to be printed.
i am newbie to programming and trying to learn java-script myself, the above is the question i am trying to solve. i am confused, i am not sure how to make the code to write the next 10 odd even number (i am referring to the first question).also the previous 5 (referring to second question).. below is my starting attempt. i am stuck
function isEven {
var value = prompt("");
if (value % 2 == 0) {
for (var i = 2; i <= ; i = i + 2;)
document.write(i + "<br>");
}
}
isEven();
Answer 1:
if(number>=0){
for(i=2;i<21;i+=2){
console.log(number+i);
}
}
Answer 2:
for(i=2;i<11;i+=2){
if((number-i)>=0){
console.log(number-i);
}
}
1) If I enter an even number, I want next 10 even numbers to be printed. If I enter an odd number, I want next 10 odd numbers to be printed.
function function1() {
var value = prompt("");
value = parseInt(value);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
document.write(value + "<br>");
}
}
2)If I enter an even number, I want previous 5 even numbers to be printed. If I enter an odd number, I want previous 5 odd numbers to be printed.
function function2() {
var value = prompt("");
value = parseInt(value);
for (var i = 1; i <= 5; i = i + 1){
value = value - 2;
document.write(value + "<br>");
}
}
Just to clarify. You want to print both the previous 5 numbers and next 10 numbers of same 'evenness' for any given number?
In which case, you should do just that... You dont need to care if the number is even or odd, because the next/previous is always 2 away. (What you do when you cross 0 is up to you)
for (var i = 1; i <= 5; i++)
document.write((INPUT - (i*2)) + "<br>");
for (var i = 1; i <= 10; i++)
document.write((INPUT + (i*2)) + "<br>");
refer this woking demo. hope this will help to you.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<style type="text/css">
</style>
<body>
Enter a number : <input type="number" id="num">
<button id="butp" class="chk">print previous five numbers</button>
|| <button id="butn" class="chk">print next ten numbers</button>
<ul id="print">
</ul>
<script type="text/javascript">
$(".chk").click(function(){
var the_id = $(this).attr('id');
//alert(the_id);
var theVal = parseInt($("#num").val());
if (the_id =="butp") //this means user asking for previous
{
if (theVal==0 || theVal < 10)
{
alert("cannot continue the operation, please enter a valid nubmer to continue");
}
else
{
for (var i=1;i<6;i++)
{
newVal = theVal - (i*2);
$("#print").append($("<li>"+newVal+"</li>"));
}
}
}
else // this means user asking for next
{
for (var i = 1;i<11;i++)
{
if (theVal==0)
{
alert("please enter a valid number to continue");
}
else
{
newVal = theVal + (i*2);
$("#print").append($("<li>"+newVal+"</li>"));
}
}
}
});
$("#num").on('change keyup keydown', function(){
theVal = $(this).val();
if (theVal == "")
{
$("#print li").css({"display":"none"})
}
})
</script>
</body>
</html>
function evenOdd(value) {
if(value%2==0){
console.log(`it's and even number ${value} next 3 digit will be`);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
console.log(value);
}
}else{
console.log(`it's and odd number ${value} next 3 digit will be`);
for (var i = 1; i <= 10; i = i + 1){
value = value + 2;
console.log(value);
}
}
}
evenOdd(13)

Categories