Display JavaScript Math Result - javascript

I am having trouble displaying a math function, there is nothing stated wrong in the console, so I do not know where I am going wrong. the output does not display the correct answer here...
Desired outcome: enter number in each input, and javascript multiplies those two input values then displays the result when you click the button.
var money = document.getElementById('money').value;
var years = document.getElementById('years').value;
var output = document.getElementById('output');
var myOutput = money * years;
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
output.innerHTML = myOutput;
})
<body>
<h4>how much money do you make a year?</h4>
<input id="money" type="number" placeholder="$$$"></input>
<input id="years" type="number" placeholder="years"></input>
<div id="output">
</div>
<button id="btn" type="button">go</button>
</body>

I would structure it like this:
const btn = document.getElementById('btn');
const money = document.getElementById('money');
const years = document.getElementById('years');
const output = document.getElementById('output');
btn.addEventListener('click', () => {
output.innerHTML = Number(money.value) * Number(years.value);
})
<body>
<h4>how much money do you make a year?</h4>
<input id="money" type="number" placeholder="$$$"></input>
<input id="years" type="number" placeholder="years"></input>
<div id="output">
</div>
<button id="btn" type="button">go</button>
</body>
As others have said, you need to move the logic inside the click handler. (In your code as it's structured, you get the two values once, at the load of the script and never update them.)
I have also broken out the searching of the DOM nodes from the calculation; it's probably a good practice for anytime such changes can happen more than once.
Finally, I converted the String values you'll get from the form elements into numbers before doing any work with them. This is generally necessary, although because of some Javascript magic, you don't actually have to do it here. (Try changing from multiplication to addition to see the dangers of forgetting this.)

When you init your application, your input fields don't have any value filled yet.
var money = document.getElementById('money');
var years = document.getElementById('years');
var output = document.getElementById('output');
const btn = document.getElementById('btn');
function calc(val1, val2) {
return Number(val1.value) * Number(val2.value);
}
btn.addEventListener('click', (e) => {
output.innerHTML = calc(money, years);
});
<body>
<h4>how much money do you make a year?</h4>
<input id="money" type="number" placeholder="$$$"></input>
<input id="years" type="number" placeholder="years"></input>
<div id="output">
</div>
<button id="btn" type="button">go</button>
</body>

You need to set the innerHTML of the element. You want to get the user input values after the click of the button. Therefore, you move your variables inside the callback function
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
var money = document.getElementById('money').value;
var years = document.getElementById('years').value;
var output = document.getElementById('output');
output.innerHTML = money * years;
})
<body>
<h4>how much money do you make a year?</h4>
<input id="money" type="number" placeholder="$$$"></input>
<input id="years" type="number" placeholder="years"></input>
<div id="output">
</div>
<button id="btn" type="button">go</button>
</body>

Try this set inner html of div and have everything but the btn element happen on click:
const btn = document.getElementById('btn');
btn.addEventListener('click', () => {
var money = document.getElementById('money').value;
var years = document.getElementById('years').value;
var output = document.getElementById('output');
var myOutput = money * years;
output.innerHTML = myOutput;
})
<body>
<h4>how much money do you make a year?</h4>
<input id="money" type="number" placeholder="$$$"></input>
<input id="years" type="number" placeholder="years"></input>
<div id="output">
</div>
<button id="btn" type="button">go</button>
</body>

Related

why am i getting undefined error from input value?

so, when i console.log document.getElementById("deposit-amount").value I get real time numbers/data. But when I put it into variable and console.log the name (depositAmount), it shows undefined.
html
<div class="deposit">
<h4>Deposit</h4>
<input id="deposit-amount" type="number" placeholder="$ amount you want to deposit">
<button id="deposit-btn">Deposit</button>
</div>
js
const depositAmount = document.getElementById("deposit-amount").value;
Seems to work fine in this snippet. Is there any more code you can share to debug?
function log() {
console.log(document.getElementById('deposit-amount').value);
}
<div class="deposit">
<h4>Deposit</h4>
<input id="deposit-amount" type="number" placeholder="$ amount you want to deposit">
<button id="deposit-btn" onclick="log()">Deposit</button>
</div>
<div class="box-1 common-box">
<p>Deposit</p>
<h2>$ <span id="current-deposit">01</span></h2>
</div>
<div class="deposit">
<h4>Deposit</h4>
<input id="deposit-amount" type="number" placeholder="$ amount you want to deposit">
<button id="deposit-btn">Deposit</button>
</div>
const depositBtn = document.getElementById("deposit-btn");
depositBtn.addEventListener("click", function(){
const depositAmount = document.getElementById("deposit-amount").value;
const depositNumber = parseFloat(depositAmount);
const cuurentDeposit = document.getElementById("current-deposit").innerText;
const currentNumber = parseFloat(cuurentDeposit);
const total = depositNumber + currentNumber;
document.getElementById("current-deposit").innerText = total;
document.getElementById("deposit-amount").value = "";
})
This works. but still when I console.log the name (depositAmount), it shows undefined.Is this because DOM isn't ready? How to resolve this? -#nemo

Getting NaN In Building a Simple Calculator

I'm fairly new to Javascript and I'm currently working on a simple calculator that would allow users to answer a few questions in order to calculate their total price. The price would show up in the DIV below the form. But, the issue that I'm having is that the output in the div is NaN until the last option is selected.
The code isn't perfect since I'm just testing at this point, but here's the HTML.
const looks = document.getElementById('looks');
const edits = document.getElementById('edits');
const studio = document.getElementById('studio');
const total = document.getElementById('total');
const btn = document.getElementById('btn')
looks.addEventListener('change', totalCost);
edits.addEventListener('change', totalCost);
studio.addEventListener('change', totalCost);
btn.addEventListener('click', totalCost);
function totalCost() {
total.innerText = (looks.value * 100)
+ (edits.value * 50)
+ parseInt(studio.value);
}
<div class="container">
<form action="">
<h3>How Many Looks?</h3>
<input type="number" id="looks" value="">
<h3>How Many Edits?</h3>
<input type="number" id="edits" value="">
<h3>Location:</h3>
<select name="studio" id="studio">
<option value="">On-Location</option>
<option value="100">In-Studio</option>
</select>
<h3>Total:</h3>
<div id="total"></div>
<input type="button" value="submit" id="btn">
</form>
</div>
I'd also like to implement something where the total doesn't show up until the submit button is pressed. I'd greatly appreciate any help in these matters. Thanks a lot!
You have an issue in studio.value, its come NaN for first init, you need to check your param if its number or not before do a calculation or convert it to number like below example:
const looks = document.getElementById('looks');
const edits = document.getElementById('edits');
const studio = document.getElementById('studio');
const total = document.getElementById('total');
const btn = document.getElementById('btn')
looks.addEventListener('change', totalCost);
edits.addEventListener('change', totalCost);
studio.addEventListener('change', totalCost);
btn.addEventListener('click', totalCost);
function totalCost() {
let stdValue = parseInt(studio.value);
if(isNaN(stdValue)){
stdValue = 0;
}
total.innerText = ((looks.value * 100)
+ (edits.value * 50)
+ stdValue);
}
<div class="container">
<form action="">
<h3>How Many Looks?</h3>
<input type="number" id="looks" value="">
<h3>How Many Edits?</h3>
<input type="number" id="edits" value="">
<h3>Location:</h3>
<select name="studio" id="studio">
<option value="">On-Location</option>
<option value="100">In-Studio</option>
</select>
<h3>Total:</h3>
<div id="total"></div>
<input type="button" value="submit" id="btn">
</form>
</div>
====================
Update 1:
Like Nick Parsons Suggestion, the real answer must be via set the 0 as a default option if its needed as a number...
<option value="0">On-Location</option>
So that, look when and where you need to validate and when need to setup initial value...do both to get a good code...
this way
const
myForm = document.getElementById('my-form')
, total = document.getElementById('total')
;
myForm.oninput = evt =>
{
total.textContent = (myForm.looks.valueAsNumber * 100)
+ (myForm.edits.valueAsNumber * 50)
+ (parseInt(myForm.studio.value) || 0)
}
myForm.onsubmit = evt => // beter than btn.onclick
{
evt.preventDefault() // stop form submiting
}
<div class="container">
<form action="" id="my-form">
<h3>How Many Looks?</h3>
<input type="number" name="looks" value="0" min="0">
<h3>How Many Edits?</h3>
<input type="number" name="edits" value="0" min="0">
<h3>Location:</h3>
<select name="studio" >
<option value="" selected > On-Location </option>
<option value="100" > In-Studio </option>
</select>
<h3>Total:</h3>
<div id="total"> ? </div>
<button type="submit">submit</button>
</form>
</div>

How do I delete document.write() out of my calculator

How do I make this calculator display the result on the first page after the ='s sign without destroying all of the html on the page with document.write()?
I know that document.write() is the problem, but I don't know of anything else to use. I'm very new to coding, so any help is greatly appreciated.
I also have a problem with the division part because it is putting the result right next to the remainder, however, once the document.write() problem is resolved, I think that the solution should become more apparent. Thank You!
<head>
<script language="javascript" type="text/javascript">
function add() {
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1 + input2;
document.write(result);
}
function divide() {
var input1 = parseInt(document.getElementById("t3").value);
var input2 = parseInt(document.getElementById("t4").value);
var result = Math.floor(input1 / input2);
var remainder = input1 % input2
document.write(result)
document.write(remainder)
}
function multiply() {
var input1 = parseInt(document.getElementById("t5").value);
var input2 = parseInt(document.getElementById("t6").value);
var result = input1 * input2;
document.write(result);
}
function subtract() {
var input1 = parseInt(document.getElementById("t7").value);
var input2 = parseInt(document.getElementById("t8").value);
var result = input1 - input2;
document.write(result);
}
</script>
<title>java</title>
</head>
<body>
Addition
<p>
<input type="text" id="t1" name="t1"> +
<input type="text" id="t2" name="t2">
<input type="button" id="add" value="=" onClick="add();">
</p>
<p>
Subtraction
<p>
<input type="text" id="t7" name="t7"> -
<input type="text" id="t8" name="t8">
<input type="button" id="subtract" value="=" onClick="subtract();">
<p>Multiplication
<p>
<input type="text" id="t5" name="t5"> *
<input type="text" id="t6" name="t6">
<input type="button" id="multiply" value="=" onClick="multiply();">
</p>
<p>Division
<p>
<input type="text" id="t3" name="t3"> ÷
<input type="text" id="t4" name="t4">
<input type="button" id="divide" value="=" onClick="divide();">
</p>
</body>
</html>
You can either use textContent or innerHTML.
Here's an example using textContent:
function add() {
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1 + input2;
document.getElementById('add-result').textContent = result;
}
function divide() {
var input1 = parseInt(document.getElementById("t3").value);
var input2 = parseInt(document.getElementById("t4").value);
var result = Math.floor(input1 / input2);
var remainder = input1 % input2
document.getElementById('divide-result').textContent = result;
document.getElementById('divide-remainder').textContent = remainder;
}
function multiply() {
var input1 = parseInt(document.getElementById("t5").value);
var input2 = parseInt(document.getElementById("t6").value);
var result = input1 * input2;
document.getElementById('multiply-result').textContent = result;
}
function subtract() {
var input1 = parseInt(document.getElementById("t7").value);
var input2 = parseInt(document.getElementById("t8").value);
var result = input1 - input2;
document.getElementById('subtract-result').textContent = result;
}
<div>
<h1>Addition</h1>
<input type="text" id="t1" name="t1"> +
<input type="text" id="t2" name="t2">
<input type="button" id="add" value="=" onClick="add();">
<span id="add-result"></span>
</div>
<div>
<h1>Subtraction</h1>
<input type="text" id="t7" name="t7"> -
<input type="text" id="t8" name="t8">
<input type="button" id="subtract" value="=" onClick="subtract();">
<span id="subtract-result"></span>
</div>
<div>
<h1>Multiplication</h1>
<input type="text" id="t5" name="t5"> *
<input type="text" id="t6" name="t6">
<input type="button" id="multiply" value="=" onClick="multiply();">
<span id="multiply-result"></span>
</div>
<div>
<h1>Division</h1>
<input type="text" id="t3" name="t3"> ÷
<input type="text" id="t4" name="t4">
<input type="button" id="divide" value="=" onClick="divide();">
<span id="divide-result"></span> |
<span id="divide-remainder"></span>
</div>
With textContent you can only set text, with innerHTML you can set HTML:
function add() {
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1 + input2;
document.getElementById('add-result').innerHTML = `<i style="color: blue">${result}</i>`;
}
function divide() {
var input1 = parseInt(document.getElementById("t3").value);
var input2 = parseInt(document.getElementById("t4").value);
var result = Math.floor(input1 / input2);
var remainder = input1 % input2
document.getElementById('divide-result').innerHTML = `<i style="color: blue">${result}</i>`;
document.getElementById('divide-remainder').innerHTML = `<i style="color: blue">${remainder}</i>`;
}
function multiply() {
var input1 = parseInt(document.getElementById("t5").value);
var input2 = parseInt(document.getElementById("t6").value);
var result = input1 * input2;
document.getElementById('multiply-result').innerHTML = `<i style="color: blue">${result}</i>`;
}
function subtract() {
var input1 = parseInt(document.getElementById("t7").value);
var input2 = parseInt(document.getElementById("t8").value);
var result = input1 - input2;
document.getElementById('subtract-result').innerHTML = `<i style="color: blue">${result}</i>`;
}
<div>
<h1>Addition</h1>
<input type="text" id="t1" name="t1"> +
<input type="text" id="t2" name="t2">
<input type="button" id="add" value="=" onClick="add();">
<span id="add-result"></span>
</div>
<div>
<h1>Subtraction</h1>
<input type="text" id="t7" name="t7"> -
<input type="text" id="t8" name="t8">
<input type="button" id="subtract" value="=" onClick="subtract();">
<span id="subtract-result"></span>
</div>
<div>
<h1>Multiplication</h1>
<input type="text" id="t5" name="t5"> *
<input type="text" id="t6" name="t6">
<input type="button" id="multiply" value="=" onClick="multiply();">
<span id="multiply-result"></span>
</div>
<div>
<h1>Division</h1>
<input type="text" id="t3" name="t3"> ÷
<input type="text" id="t4" name="t4">
<input type="button" id="divide" value="=" onClick="divide();">
<span id="divide-result"></span> |
<span id="divide-remainder"></span>
</div>
It's worth noting, with innerHTML there are security concerns as mentioned here:
...there are ways to execute JavaScript without using elements, so there is still a security risk whenever you use innerHTML to set strings over which you have no control. For example:
const name = "<img src='x' onerror='alert(1)'>";
el.innerHTML = name; // shows the alert
For that reason, it is recommended that you do not use innerHTML when inserting plain text; instead, use Node.textContent. This doesn't parse the passed content as HTML, but instead inserts it as raw text.
Here are some other methods used to manipulate the DOM:
insertAdjacentElement
innerText
insertAdjacentHTML
insertAdjacentText
insertBefore
appendChild
replaceChild
removeChild
nodeValue
outerHTML
outerText
remove
See the full list here.
As you have discovered, document.write() is tricky because it has a tendency to overwrite the existing content when used. Let's see what the documentation has to say about it:
Note: Because document.write() writes to the document stream, calling document.write() on a closed (loaded) document automatically calls document.open(), which will clear the document.
Hmm, well what else can we do? Fortunately, it is possible to target specific parts of the page and replace content in those elements only. So, for example we could add <span> elements with ids like #add-result, #div-result etc to the page which will contain the results of their respective action. Then, instead of using document.write() to output the results, we can replace the content in those elements.
Let's add a <span> to contain our add result:
Addition<p>
<input type="text" id="t1" name="t1" /> +
<input type="text" id="t2" name="t2" />
<input type="button" id="add" value="=" onClick="add();" />
<span id="add-result></span>
</p>
(Note: remember to close your <input /> tags with a />!)
How do we target a specific element? With document.querySelector(). Docs
Then, we can easily change the content inside of that element by updating the element.textContent property, just like you would a variable:
function add(){
var input1 = parseInt(document.getElementById("t1").value);
var input2 = parseInt(document.getElementById("t2").value);
var result = input1+input2;
// get the element with the #add-result ID
var element = document.querySelector("#add-result");
// update the content in that element
element.textContent = result;
}
Now when you add two numbers together and press =, the result will appear inside of the <span id="add-result"></span> element instead of overwriting the entire page. See if you can get it working for the other inputs as well. Remember you will need a unique id for each element you want to display a result in, and update the calculation functions accordingly!

Why isn't my code adding a number with the input field (HTML/Javascript - Beginner)?

for practice as a beginner I am trying to take a number from a text field, have the user press a button that adds 2 to that number, and then displays it through HTML. However, for some reason I keep getting NaN when applying the code below.
//Setup
var num1 = document.querySelector(".input-box").value;
var btn = document.querySelector(".btn");
//Add
var sum = parseInt(num1) + 2;
btn.addEventListener('click', (e) => {
e.preventDefault();
document.querySelector("#output").innerHTML = sum;
})
<html>
<head>
<title>Calculate</title>
<style>
</style>
</head>
<body>
<div class="sign">
<h1>Calculate</h1>
<form>
<input type="text" class="input-box" placeholder="Enter Number">
<input class="btn" type="button" value="Add 2">
</form>
<h1 id="output"></h1>
</div>
<script src="manip3.js"></script>
</body>
</html>
You need to move the num1 and sum the inside the event listener
//Setup
var btn = document.querySelector(".btn");
//Add
btn.addEventListener('click', (e) => {
e.preventDefault();
// get the number
var num1 = document.querySelector(".input-box").value;
// add 2
var sum = parseInt(num1) + 2;
document.querySelector("#output").innerHTML = sum;
})
<html>
<head>
<title>Calculate</title>
<style>
</style>
</head>
<body>
<div class="sign">
<h1>Calculate</h1>
<form>
<input type="text" class="input-box" placeholder="Enter Number">
<input class="btn" type="button" value="Add 2">
</form>
<h1 id="output"></h1>
</div>
<script src="manip3.js"></script>
</body>
</html>
You need to calculate the sum inside the click function. Right now it is calculating before the butten is clicked, when the page loads, which means the input is empty.
as mentioned above you need to resolve after the button is clicked. you could change your variables to function variables.
//Setup
var num1 = function() {return document.querySelector(".input-box").value};
var btn = document.querySelector(".btn");
//Add
var sum = function() {return parseInt(num1()) + 2};
btn.addEventListener('click', (e) => {
e.preventDefault();
document.querySelector("#output").innerHTML = sum();
})
make the input type = number for better validation
make the button type = submit cause this is form and you need to submit
add submit event to the form cause you can't prevent default without submit event
select input inside the event and convert its value to number by adding + before it
// select from
var form = document.getElementById("form");
form.addEventListener('submit', (e) => {
e.preventDefault();
// select input and convert its value to number
var num1 = +document.querySelector(".input-box").value;
document.querySelector("#output").innerHTML = num1 + 2;
// wipe out form after submit
form.reset();
});
<div class="sign">
<h1>Calculate</h1>
<form id="form">
<input type="number" class="input-box" placeholder="Enter Number">
<input class="btn" type="submit" value="Add 2">
</form>
<h1 id="output"></h1>
</div>

Getting number from user input: string is empty on submit?

I'm stuck on a problem. I'm working on an exercise that generates a random integer between 1-10. The user will submit a number from 1-10 in the input box. If a match occurs, the user will get an alert notifying them of success.
I'm stuck on getting the number from the user input. I want to log to the console the form input, but for the life of me, I cannot figure this out. I've tried changing the form type="number", type="text" and tried using parseInt().
Anything glaring in my code?
function exerciseEight() {
let input = document.querySelector("#number").value;
let button = document.querySelector("#guess");
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
button.onclick = function() {
console.log(input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
You need to get the input value when the user clicks. You're setting input and all the other variables that depend on it when the page is first loaded.
function exerciseEight() {
let button = document.querySelector("#guess");
let number = Math.ceil(Math.random() * 10);
button.onclick = function() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
console.log(number, input);
};
}
exerciseEight();
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>
The problem is that you are calling the function when the page loads, so it gets the values from the start, and doesn't change them at runtime when user enters input. You should call the function when user clicks the button.
function exerciseEight() {
let input = document.querySelector("#number").value;
let valueInt = parseInt(input, 10);
let number = Math.ceil(Math.random() * 10);
console.log(number);
}
let button = document.querySelector("#guess");
button.onclick = exerciseEight;
<body>
<div class="container container-fluid">
<p><strong>Exercise Eight:</strong> Guess a Number between 1 and 10.</p>
<form>
<div class="form-group">
<label for="number">Choose Number:</label>
<input id="number" value="" type="text" name="number" />
</form>
<!-- Result will go here -->
<p id="result"></p>
</div>
<button class="btn btn-dark" id="guess" type="submit">SUBMIT</button>
</body>

Categories