Global variable placement for functions - javascript

I'm currently taking a JavaScript class and have the following assignment:
"Design a JavaScript program that asks the user for two numbers, and then sends these two numbers as arguments to four arithmetic functions: addition, multiplication, division, and modulus... The functions should return the values to the calling module, where they're displayed."
<body>
<h1>Number Functions</h1>
<!-- FORM START -->
<form name="Numbers">
First number:
<br/>
<input type="number" name="number1"/>
<br/>
Second Number:
<br/>
<input type="number" name="number2"/>
<p/>
<input type="button" value="Submit" onclick="showInfo()"/>
<p/>
<textarea rows="8" colspan="150" name="info" readonly="true" value=""></textarea>
</form>
<script type="text/javascript">
function showInfo() {
// Declare and get variables
var firstNumber = parseFloat(document.Numbers.number1.value); // first number
var secondNumber = parseFloat(document.Numbers.number2.value); // second number
// Four mathematical functions
function add(num1, num2) {
var sum = num1 + " + " + num2 + " = " + (num1+num2).toFixed(2) + "\n";
return sum;
}
function multiply(num1, num2) {
var product = num1 + " \u00d7 " + num2 + " = " + (num1*num2).toFixed(2) + "\n";
return product;
}
function divide(num1, num2) {
var dividend = num1 + " / " + num2 + " = " + (num1/num2).toFixed(2) + "\n";
return dividend;
}
function modulus(num1, num2) {
var surplus = num1 + " % " + num2 + " = " + (num1%num2).toFixed(2);
return surplus;
}
var total = add(firstNumber,secondNumber) + multiply(firstNumber,secondNumber) + divide(firstNumber,secondNumber) + modulus(firstNumber,secondNumber);
document.Numbers.info.value = total;
// I need this function to get the results from the four above and put them in the textarea!
}
</script>
</body>
I'm not exactly sure how I should be getting the results of these four functions and displaying the results, but I do suspect that a lot of the reasons my code isn't working is because of incorrect variable placement. This is an online class and the textbook is horrible! So if you could point me in the right direction (or multiple correct directions), that'd be great.

There are a lot of things wrong with this.
First, you shouldn't set num1 and num2 at the very top of your script. They will start out not set, so you should retrieve them in your showInfo function.
You aren't returning anything from your functions, which you should be
You aren't actually calling your functions in showInfo, you are coercing them to a string, and thus seeing odd behavior.
It sounds like you should be passing in num1 and num2, not relying on a global variable to access them. You need to pass them and have each function accept two variables.
Try something like this fiddle: https://jsfiddle.net/oLb1vzrb/
// Four mathematical functions
function add(num1, num2) {
return num1 + " + " + num2 + " = " + (num1 + num2).toFixed(2);
}
function multiply(num1, num2) {
return num1 + " \u00d7 " + num2 + " = " + (num1 * num2).toFixed(2);
}
function divide(num1, num2) {
return num1 + " / " + num2 + " = " + (num1 / num2).toFixed(2);
}
function modulus(num1, num2) {
return num1 + " % " + num2 + " = " + (num1 % num2).toFixed(2);
}
function showInfo() {
// Declare and get variables
var num1 = parseFloat(document.Numbers.number1.value); // first number
var num2 = parseFloat(document.Numbers.number2.value); // second number
document.Numbers.info.value = add(num1, num2) + multiply(num1, num2) + divide(num1, num2) + modulus(num1, num2);
}

Related

How can I use Prompt, if and else in Javascript function to select arithmetic symbol and do some calculation with the user inputs

I am a novice in this and it is really making me to lose my hair; I can find what I'm doing wrong, please help. I am doing this in javascript. It doesn't show any error, nor display any result either. This is what I have:
var sumIt;
var subtractIt;
var multiplyIt;
var divideIt;
var operatorOpt = prompt("Select operator");
function showResult(whatResult) {
document.write(whatResult);
document.write("<br>");
}
var doSomething = function(num1, num2) {
if (operatorOpt == sumIt) {
showResult("The result is: " + (num1 + num2));
} else if (operatorOpt == subtractIt) {
showResult("The result is: " + (num1 - num2));
} else if (operatorOpt == multiplyIt) {
showResult("The result is: " + (num1 * num2));
} else if (operatorOpt == divideIt) {
showResult("The result is: " + (num1 / num2));
doSomething(parseInt (prompt("Enter first number: ")) , parseInt (prompt("Enter second number: ")))
It seems that your are missing a closed bracket in the definition of doSomething function.
The following code seems to work produce the desired results
var sumIt = "+";
var subtractIt = "-";
var multiplyIt = "*";
var divideIt = "/";
var operatorOpt = prompt("Select operator");
function showResult(whatResult) {
console.log(whatResult);
document.write(whatResult);
document.write("<br>");
}
var doSomething = function(num1, num2) {
if (operatorOpt == sumIt) {
showResult("The result is: " + (num1 + num2));
} else if (operatorOpt == subtractIt) {
showResult("The result is: " + (num1 - num2));
} else if (operatorOpt == multiplyIt) {
showResult("The result is: " + (num1 * num2));
} else if (operatorOpt == divideIt) {
showResult("The result is: " + (num1 / num2));
} else {
console.log("No Condition reached");
}
}
doSomething(parseInt (prompt("Enter first number: ")) , parseInt (prompt("Enter second number: ")));
Simply at the prompt create a list with the options like so:
prompt("Select operator:"
+ "\n1. Addition"
+ "\n2.Subtraction"
+ "\n3.Multiplication"
+ "\n4.Division");
Then compare the user supplied numbers whit the operator number.

The ++ operator is not functioning in JS when I tries to add one to it

I know that the question has been asked before. But it is different. So I have a score variable and I increase by 1 when a user answers a question. It works at first, and it stops working. I don't think it's a postfix or prefix.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>
Math 24
</title>
</head>
<body>
<h1>
Play this game by typing a expression that = 24. Do not type the result or the equal sign
</h1>
<p id="d">
</p>
<p id="score">
Your score: 0
</p>
<label for="Enter your expression">
Enter your expression
</label>
<input type="text" id="input">
<button onclick="myResult()">
Check
</button>
<p id="error">
</p>
<button onclick="new_puzzle()">
New Challenge
</button>
<p>
Can't solve the puzzle?
</p>
<button onclick="skip()">
Skip This One
</button>
<script>
function myResult(){
var score = 0;
var getInputValue = document.getElementById('input').value;
if(getInputValue.includes(num1, num2, num3, num4) == true){
parseInt(getInputValue);
eval(getInputValue);
}
if(eval(getInputValue) == 24){
score++;
document.getElementById('error').innerHTML = 'Great Job! You got it!';
document.getElementById('score').innerHTML = 'Your score: ' + score;
}
else if(getInputValue === ""){
document.getElementById('error').innerHTML = 'Empty field are not allowed';
}
else{
document.getElementById('error').innerHTML = 'Keep trying';
}
}
</script>
<script>
var num1 = Math.ceil(Math.random() * 9);
var num2 = Math.ceil(Math.random() * 9);
var num3 = Math.ceil(Math.random() * 9);
var num4 = Math.ceil(Math.random() * 9);
String(num1, num2, num3, num4);
document.getElementById('d').innerHTML = "Your numbers are:" + num1 + ' ' + num2 + ' ' + num3 + ' ' + num4;
</script>
<script>
function new_puzzle(){
var num1 = Math.ceil(Math.random() * 9);
var num2 = Math.ceil(Math.random() * 9);
var num3 = Math.ceil(Math.random() * 9);
var num4 = Math.ceil(Math.random() * 9);
String(num1, num2, num3, num4);
document.getElementById('d').innerHTML = "Your numbers are:" + num1 + ' ' + num2 + ' ' + num3 + ' ' + num4;
document.getElementById('error').style.display === "none";
}
</script>
<script>
function skip(){
var num1 = Math.ceil(Math.random() * 9);
var num2 = Math.ceil(Math.random() * 9);
var num3 = Math.ceil(Math.random() * 9);
var num4 = Math.ceil(Math.random() * 9);
String(num1, num2, num3, num4);
document.getElementById('d').innerHTML = "Your numbers are:" + num1 + ' ' + num2 + ' ' + num3 + ' ' + num4;
document.getElementById('error').style.display === "none";
}
</script>
</body>
</html>
The score should increase by one whenever a question is answered correctly.
Every time the button is clicked, the myResult function is called which redefines score as 0. You can try making score a global variable by taking the declaration out of the function.

“Syntax errors” appearing even though none seem to be present

I am writing a code that produces a random math quiz. However, when I run it (in an app called SoloLearn) it I get a Syntax error even though there doesn’t appear to be any. I even tested it in JSHint and no Syntax errors seemed to be present. Here is my code:
function random(max) {
return Math.floor(Math.random() * Math.floor(max));
}
function start() {
var form = document.getElementById("name_form");
var name = form.elements[0].value;
var score = 0;
alert("Let's begin!");
for (let i = 0; i < 4; i++) {
var num1 = random(10);
var num2 = random(10);
var operator = random(2);
if (operator == 0) {
var question = prompt(num1 + " + " + num2 + " =");
var answer = num1 + num2;
}
else {
var question = prompt(num1 + " - " + num2 = " =");
var answer = num1 - num2;
}
if (question == answer) {
alert("Correct!");
score++;
}
else {
alert("Incorrect ):");
}
}
document.write(score);
}
What is going on here?
In your line var question = prompt(num1 + " - " + num2 = " ="); you have misspelled a '+' which is a '=' in your code.
It should be:
var question = prompt(num1 + " - " + num2 + " =");
The same as #Nick Parsons said in the comments
Syntax error should be fixed by changing
var question = prompt(num1 + " - " + num2 = " =");
to
var question = prompt(num1 + " - " + num2 + " =");
which is the intent I believe

Replacing a string of code in html in JS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I'm new here and this is my first issue I've put up. This literally might be so easy for some of you it's not even funny. I need to replace and/or erase a string for this to fit. I've tried cutting out multiple lines near the end but I can't seem to get it to work for me. ALSO I'm using notepad++
Original string:
var num1;
var num2;
var answer;
num1 = prompt("Enter a number ");
num2 = prompt("Enter a number ");
document.write("You entered " + num1 + " and " + num2);
document.write("<br>");
answer = prompt("Enter the sum of " + num1 + " and " + num2);
document.write("You entered " + answer);
document.write("<br>");
num1 = parseInt(num1);
num2 = parseInt(num2);
var sum = num1 + num2;
document.write("The sum is " + sum);
<html>
<body>
</body>
</html>
String that I need to insert:
if (answer == sum) {
document.write("That is correct!");
} else {
document.write("That is not correct. The correct answer is " + sum);
}
Create a <span> element to house the completion message:
<span id="answerMessage"></span>
Then you can apply the message that that span by:
document.getElementById("answerMessage").innerHTML = "Correct!";
That way there's no erasing or printing required for this message.
Edit
If your application is designed to look like a command based system with a fully printed history then ignore this solution. I provided this because that wasn't obvious in your question.
var num1;
var num2;
var answer;
num1 = prompt("Enter a number ");
num2 = prompt("Enter a number ");
document.write("You entered " + num1 + " and " + num2);
document.write("<br>");
answer = prompt("Enter the sum of " + num1 + " and " + num2);
document.write("You entered " + answer);
document.write("<br>");
num1 = parseInt(num1);
num2 = parseInt(num2);
var sum = num1 + num2;
if (answer == sum) {
document.write("That is correct!");
} else {
document.write("That is not correct. The correct answer is " + sum);
}
document.write("The sum is " + sum);
Something like this should work
This works here (in Firefox):
<!DOCTYPE html>
<html>
<body>
<script>
var num1;
var num2;
var answer;
num1 = prompt("Enter a number ");
num2 = prompt("Enter a number ");
document.write("You entered " + num1 + " and " + num2);
document.write("<br>");
answer = prompt("Enter the sum of " + num1 + " and " + num2);
document.write("You entered " + answer);
document.write("<br>");
num1 = parseInt(num1);
num2 = parseInt(num2);
var sum = num1 + num2;
document.write("The sum is " + sum);
document.write("<br>");
if (answer == sum) {
document.write("That is correct!");
} else {
document.write("That is not correct. The correct answer is " + sum);
}
</script>
</body>
</html>

No prompt from JS

This code only gets me to link address but doesn't run the function. (the last alert() function doesn't run).
I need this alert, what I am doing wrong?
Here is my code:
<html>
<head>
<title>Laboratorul nr_3</title>
<meta charset="utf-8"/>
<script language="javascript"><!--
function ex1()
{
num = prompt("Input the number");
result = num * 3;
alert(num + " x " + 3 + " = " + result);
num2 = prompt("Input number to add");
result2 = num * 3 + parseint(num2);
alert(num + " x " + 3 + " + " num2 " = " + result2);
}
//--></script>
</head>
<body>
link
</body>
</html>
You have to cancel the native action (following the link):
function ex1() {
// code...
return false;
}
Or use a different element that doesn't do anything, maybe a <button> or <div>.
There was only 3 errors you didn't call the function and you didn't concate the string and the parseInt, int cannot be spelled in lower case
function ex1(){
num = prompt("Input the number");
result = num * 3;
alert(num + " x " + 3 + " = " + result);
num2 = prompt("Input number to add");
result2 = num * 3 + parseInt(num2);
alert(num + " x " + 3 + " + " + num2 +" = " + result2);
}
ex1()

Categories