JavaScript multiplication programs do not work normally - javascript

var num1 = Math.floor(Math.random()*9 + 1);
var num2 = Math.floor(Math.random()*9 + 1);
var num_multiple = num1 * num2;
var form = document.querySelector('form');
var input = form.querySelector('input');
var button = form.querySelector('button');
var quesiton = document.querySelector('.p1');
var result = document.querySelector('.p2');
quesiton.textContent = String(num1) + " multiplication " + String(num2) + " = ? ";
form.addEventListener("submit",function(e){
e.preventDefault;
if(num_multiple === Number(input.value)){
num1 = Math.floor(Math.random()*9 + 1);
num2 = Math.floor(Math.random()*9 + 1);
num_multiple = num1 * num2;
quesiton.textContent = String(num1) + " multiplication " + String(num2) + " = ? ";
input.value = "";
result.textContent = "good";
input.focus();
}
else{
input.value = "";
result.textContent = "bad";
input.focus();
}
})
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div><p class="p1"></p></div>
<form>
<input type="text">
<button>submit</button>
</form>
<div><p class="p2"></p></div>
<script src="multiple.js"></script>
</body>
</html>
I'm sorry that I can't speak English so I use a translator to translate it.
The problem is that if the num_multiple and number (input.value) values are equal, "good" comes out very quickly and disappears very quickly. Also, input.focus(); does not work.
The problem is that a new question is written in quesiton even though the num_multiple and number(input.value) values are not equal.
How should I fix the code?

You need to call e.preventDefault
i.e do e.preventDefault() instead of e.preventDefault. This is causing the page to reload (default submit behavior), hence the input.focus() not working

You forgot the parentheses at the end of e.preventDefault (to make it a function). Other than that I also updated your code to DRY it out. DRY stands for Don't Repeat Yourself. You had a few lines of duplicate code that I put into a single function setNumbers() to make it DRY. I also made the result.textContent lines into a single ternary operator: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator
var num1, num2, num_multiple
var form = document.querySelector('form');
var input = form.querySelector('input');
var quesiton = document.querySelector('.p1');
var result = document.querySelector('.p2');
function setNumbers(){
input.value = "";
num1 = Math.floor(Math.random() * 9 + 1);
num2 = Math.floor(Math.random() * 9 + 1);
num_multiple = num1 * num2;
quesiton.textContent = String(num1) + " multiplication " + String(num2) + " = ? ";
input.focus();
}
form.addEventListener("submit", function(e) {
e.preventDefault();
var correctAnswer = num_multiple === Number(input.value);
result.textContent = correctAnswer ? "good" : "bad";
if(correctAnswer){
setNumbers()
}
})
setNumbers()
<div>
<p class="p1"></p>
</div>
<form>
<input type="text">
<button>submit</button>
</form>
<div>
<p class="p2"></p>
</div>
<script src="multiple.js"></script>

Related

Can I convert an getElementbyId into a number to make a math operation in JavaScript?

This is a basic calculator project. I am having trouble to return the result, after any button is clicked it returns NaN. It has something to do with the input and how it translate into a number, but ".value" doesn't seem to be working
html file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calculator</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<h1>Calculator</h1>
<input type="text" id="num1-el">
<input type="text" id="num2-el">
<button onclick="add()">Add</button>
<button onclick="subtract()">Subtract</button>
<button onclick="divide()">Divide</button>
<button onclick="multiply()">Multiply</button>
<p id="sum-el">Sum: </p>
<script src="/script.js"></script>
</body>
</html>
In the JS file I can see that the variables get the elements but it can't make a math operations with them, even with parseInt and .value
JavScript file:
let num1 = parseInt(document.getElementById("num1-el").value)
let num2 = parseInt(document.getElementById("num2-el").value)
let sum = document.getElementById("sum-el")
let operation
function add() {
operation = num1 + num2;
sum.textContent += operation + " | ";
}
function subtract() {
operation = num1 - num2;
sum.textContent += operation + " | ";
}
function divide() {
operation = num1 / num2;
sum.textContent += operation + " | ";
}
function multiply() {
operation = num1 * num2;
sum.textContent += operation + " | ";
}
Can someone help with this please? Thank you!
ps: This is my first question in stack overflow and english is not my first language, so I apologize in advance for any basic mistake
When the script runs, num1 and num2 get their values just one first time, and both would be undefined. Therefor when you click the buttons and trigger functions, all results would be NaN.
Try this way:
let num1, num2
function getNumbers() {
num1 = parseInt(document.getElementById("num1-el").value)
num2 = parseInt(document.getElementById("num2-el").value)
}
function add() {
getNumbers();
operation = num1 + num2;
sum.textContent += operation + " | ";
}
/* other functions */

JavaScript: Combining functions and scripts and buttons

I am going through the SAMS Learn JavaScript in 24 hours book. The end of lesson three has an extra exercise to combine a Celsius to Fahrenheit from Lesson 2, with functions and buttons from Lesson 3. I was able to successfully complete the Try It exercises in Lessons 2 and 3...
LESSON 2
<!DOCTYPE html>
<html>
<head>
<title>Fahrenheit From Celsius</title>
</head>
<body>
<script>
var cTemp = 100; // temperature in Celsius
var hTemp = ((cTemp * 9) /5 ) + 32;
document.write("Temperature in Celsius: " + cTemp + " degrees<br/>");
document.write("Temperature in Fahrenheit: " + hTemp + " degrees");
</script>
LESSON 3
<!DOCTYPE html>
<html>
<head>
<title>Calling Functions</title>
<script>
function buttonReport(buttonId, buttonName, buttonValue) {
var userMessage1 = "Button id: " + buttonId + "\n";
var userMessage2 = "Button name: " + buttonName + "\n";
var userMessage3 = "Button value: " + buttonValue;
alert(userMessage1 + userMessage2 + userMessage3);
}
</script>
But I am stuck combining the two.
EXERCISE TO COMBINE THE TWO:
Write a function to take a temperature value in Celsius as an argument and return the equivalent temperature in Fahrenheit, basing it on the code from Lesson 2.
Test your function in an HTML page having three buttons that, when clicked, pass values of 10, 20, and 30 degrees Celsius, respectively, to the function.
HERE'S WHAT I HAVE...(minus the headers, titles and HTML tags)
function temp(10, 20, 30) {
var hTemp1 = ((temp * 9) /5 ) + 32;
var hTemp2 = ((temp * 9) /5 ) + 32;
var hTemp3 = ((temp * 9) /5 ) + 32;
alert(hTemp1, hTemp2, hTemp3);
}
</script>
</head>
<body>
<input type="button" value="10 X Celsius" onclick = hTemp1>
<input type="button" value="20 X Celsius" onclick = hTemp2>
<input type="button" value="30 X Celsius" onclick = hTemp3>
Can you please help me?
There's definitely better ways to do this. But here's a solution for the purpose of this lesson. I tried not to change too much of your code. Check out the snippet below.
function toF(cTmp) {
return cTmp * 9 / 5 + 32
}
function alertF(tmp) {
alert(toF(tmp))
}
<input type="button" value="10" onclick="alertF(10)">
<input type="button" value="20" onclick="alertF(20)">
<input type="button" value="30" onclick="alertF(30)">

Outputting data on a webpage based on Dropdown Menu/Form Value Inputs

What I need to do is have some sort of textbox form where someone can input a number, and based on this number a variable will multiply certain values by the number of shares:
var stocks = [
['Apple', 141.63, 144.77, 90.34],
['Microsoft', 65.48, 65.78, 48.43]
];
var select = document.getElementById("selectStock");
select.onchange = (e) => {
let index = stocks.indexOf(stocks.find(a => a.indexOf(e.target.value) > -1));
document.getElementById("result").innerText =
("$" + Math.round(stocks[index][1] * 100) / 100 + " per share \n") +
("$" + Math.round(stocks[index][2] * 100) / 100 + " year high \n") +
("$" + Math.round(stocks[index][3] * 100) / 100 + " year low \n")
};
for (var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
var select = document.getElementById("selectStock1");
select.onchange = (e) => {
let index = stocks.indexOf(stocks.find(a => a.indexOf(e.target.value) > -1));
document.getElementById("result1").innerText =
("$" + Math.round(stocks[index][1] * 100) / 100 + " per share \n") +
("$" + Math.round(stocks[index][2] * 100) / 100 + " year high \n") +
("$" + Math.round(stocks[index][3] * 100) / 100 + " year low \n")
};
for (var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div style="display:block;">
<select id="selectStock">
<option>Pick a stock!</option>
<br>
<br>
<div id="result"></div>
</select>
<select id="selectStock1">
<option>Pick a stock!</option>
</select>
<br>
<br>
<div id="result"></div>
<br>
<br>
<div id="result1"></div>
</div>
</body>
So once the user inputs the number and selects a value from each dropdown menu, it provides the results side by side for comparison. I'm having trouble coming up with the code to insert a textbox and link it to my javascript code, so I'd really appreciate help on this. I'm also having trouble formatting the code so that the actual results are side by side, so I'd also appreciate help on this as well. Much appreciated!!
Add an input and also add the corresponding keyup event to monitor for changes. I wrote up an example in jQuery.
var stocks = [
['Apple', 141.63, 144.77, 90.34],
['Microsoft', 65.48, 65.78, 48.43]
];
$(".selectStock").each(function (){
for (var i = 0, len = stocks.length; i < len; i++) {
$("<option>").html(stocks[i][0]).attr("value", i).appendTo(this);
}
});
function r2d (i) {
return Math.round(i * 100) / 100
}
$(".selectStock").change(updateAmount);
$("#numberOfStocks").on('keyup', updateAmount);
function updateAmount() {
$(".selectStock").each(function () {
index = Number($(this).val());
if (isNaN(index)) {
return;
}
amt = Number($("#numberOfStocks").val());
if (isNaN(amt) || amt == 0) {
amt = 1;
}
$(this).nextAll(".result:first").html("")
.append("$" + r2d(amt*stocks[index][1]) + " per share<br />")
.append("$" + r2d(amt*stocks[index][2]) + " high year<br />")
.append("$" + r2d(amt*stocks[index][3]) + " low year<br />");
});
}
.side {
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<input value="1" type="text" id="numberOfStocks" />
<div style="display:block;">
<div class="side">
<select class="selectStock">
<option>Pick a stock!</option>
</select>
<br>
<br>
<div class="result"></div>
</div>
<div class="side">
<select class="selectStock">
<option>Pick a stock!</option>
</select>
<br>
<br>
<div class="result"></div>
</div>
</div>
</body>

JS - How to start from new line inside for loop?

I am trying to print 6 random numbers after clicking a button. Then every time I click the button again, random numbers should start from new line however I do not know how. I tried everything and nothing works. I appreciate any help.
function fname() {
for(i=1; i<=6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
var print = number + " GOOD LUCK!";
}
document.getElementById("total").value = print;
}
<!DOCTYPE html>
<html>
<head>
<title>Let's ROLL!</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
input, button {display: block;}
</style>
<script>
var number = "";
function fname() {
for(i=1; i<=6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
var print = number + " GOOD LUCK!";
}
document.getElementById("total").value = print;
}
</script>
</head>
<body>
<div>
<button onclick="fname()">ROLL!</button>
<textarea id="total" rows="12" cols="50" readonly></textarea>
</div>
</body>
</html>
Not 100% clear on where you wanted the breaks, but in a text area, a line break is \n. If this was in an HTML element, you would use <br />.
var number = "";
function fname() {
for (i = 1; i <= 6; i++) {
number = number + Math.floor(Math.random() * 47 + 1) + "-";
}
number = number + "\n";
var print = number + "GOOD LUCK!";
document.getElementById("total").value = print;
}
input,
button {
display: block;
}
<div>
<button onclick="fname()">ROLL!</button>
<textarea id="total" rows="12" cols="50" readonly></textarea>
</div>
Add "\n".
I am assuming you want to concatenate the new text in the text area, so you should use += instead of =:
document.getElementById("total").value += print + "\n";
You can use arrays and .join() the numbers and lines together by their appropriate delimiters. This only inserts the characters between the elements. \n in a string renders a new line.
var button = document.getElementById('roll');
var total = document.getElementById('total');
var rolls = [];
button.onclick = function() {
var roll = [];
for(var i=0; i<6; ++i) roll.push(Math.floor(Math.random() * 47 + 1));
rolls.push(roll.join('-'));
total.value = rolls.join('\n') + "\nGOOD LUCK!";
}
<button id="roll">ROLL!</button><br>
<textarea id="total" rows="12" cols="50" readonly></textarea>

Beginning Javascript Chapter 2 finishing exercise 2

I'm working through Beginning Javascript but can't get past Chapter 2 finishing exercise 2. The exercise is to correct this bit of code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 2, Finishing exercise 2</title>
</head>
<body>
<script>
var firstNumber = prompt("Enter the first number", "");
var secondNumber = prompt("Enter the second number", "");
var theTotal = firstNumber + secondNumber;
document.write(firstNumber + " added to " + secondNumber + " equals " theTotal);
</script>
</body>
</html>
I can get the correct total to display using alert, however when I remove the commenting it no longer works.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 2, Finishing exercise 2</title>
</head>
<body>
<script>
var firstNumber = prompt("Enter the first number", "");
var secondNumber = prompt("Enter the second number", "");
var intFirstNumber = parseInt(firstNumber, 10);
var intSecondNumber = parseInt(secondNumber, 10);
var theTotal = intFirstNumber + intSecondNumber;
alert(theTotal);
//document.write (intFirstNumber + " added to " + intSecondNumber + " equals " theTotal);
</script>
</body>
</html>
I can't figure out what about my document.write statement is wrong. Any hints? Additionally is there a more elegant way to achieve what I'm doing?
You need another + between the "equals" and theTotal:
document.write(firstNumber + " added to " + secondNumber + " equals " + theTotal);
In this context, the + sign means concatenate (append) whatever comes after it to whatever comes before it.
Further Reading:
MDN documentation for string concatenation.

Categories