Making Calculator using JavaScript but it doesn't work - javascript

I'm new to JavaScript and I decided to write a calculator but It doesn't work and I know it's correct it's not related to the code or maybe it is idk. but over 90% sure that the problem is not the code cause I wrote the same code on the internet.
I tried to write it in an external JS file so I wanted to paste it here like this that u won't get bothered.
thanks...
let result = document.querySelector('.result');
function sum() {
let num1 = document.querySelector('.num1');
let num2 = document.querySelector('.num2');
let num1 = parseInt(num1);
let num2 = parseInt(num2);
let submit = num1 + num2;
result.textContent = submit;
}
<label for="num1">Number 1 : </label>
<input type="number" class="num1" /><br><br>
<label for="num2">Number 2 : </label>
<input type="number" class="num2" /><br><br>
<input type="button" style="margin-left: 10px;" value="Submit" onclick="sum()"></button><br><br>
<label for="result">Result : </label>
<h1 class="result" />dd</h1>

Three issues in your code:
let cannot be used twice for the same variable. That gives a parse error.
There is no HTML element with id equal to "result". You should change class="result" to id="result".
The code tries to add HTML elements, but you should take the value property.
let result = document.getElementById('result');
function sum() {
let num1 = document.querySelector('.num1');
let num2 = document.querySelector('.num2');
num1 = parseInt(num1.value); // Take valeu!
num2 = parseInt(num2.value);
let submit = num1 + num2;
result.innerHTML = submit;
}
<label for="num1">Number 1 : </label>
<input type="number" class="num1" /><br><br>
<label for="num2">Number 2 : </label>
<input type="number" class="num2" /><br><br>
<input type="button" style="margin-left: 10px;" value="Submit" onclick="sum()"></button><br><br>
<label for="result">Result : </label>
<h1 id="result" />dd</h1>

I've made changes to your code.
Note:
Do not declare the variable twice.
Also use id on input tags when you use label.
function sum() {
let result = document.getElementById('result');
let num1 = document.getElementById('num1').value;
let num2 = document.getElementById('num2').value;
let num1Val = parseInt(num1);
let num2Val = parseInt(num2);
let submit = num1Val + num2Val;
result.innerHTML = submit;
}
<label for="num1">Number 1 : </label>
<input type="number" id="num1" /><br><br>
<label for="num2">Number 2 : </label>
<input type="number" id="num2" /><br><br>
<input type="button" style="margin-left: 10px;" value="Submit" onclick="sum()"><br>
<br>
<label for="result">Result : </label>
<h1 id="result"></h1>
Reference
id attribute usage
class attribute usage
I recommend you to spend some time on learning basics.
freeCodeCamp

Related

How to clear an input of type number when a button is clicked

I am making a mortgage calculator and am trying to clear all the inputs when the clear button is presses. I can't seem to get it to work. Below is my html and JavaScript code, I have also tried setting the inputs = null and that didn't work.
HTML:
<div class="calculator">
<h1>Mortgage Calculator</h1>
<div class="input-container">
<label for="Loan-amount">Total Loan Amount</label>
<input type="number" name="Loan-amount" id="total" min="0">
</div>
<div class="input-container">
<label for="down-payment">Down payment</label>
<input type="number" name="Loan-amount" id="down" min="0">
</div>
<div class="input-container">
<label for="interest-rate">Interest rate %</label>
<input type="number" name="interest-rate" id="interest" min="0">
</div>
<div class="input-container">
<label for="loan-term">Loan Term (in years)</label>
<input type="number" name="loan-term" id="duration" min="0">
</div>
<div class="answer">
<h2>Estimated payment:</h2>
<p id="paragraph-value"></p>
</div>
<div class="button-container">
<button id="submitBtn">Calculate</button>
<button id="clearBtn">Clear</button>
</div>
<p id="alert"></p>
</div>
JavaScript:
const clearBtn = document.querySelector("#clearBtn");
clearBtn.addEventListener("click", function (e) {
let total = document.getElementById("total").value;
let interest = document.querySelector("#interest").value;
let duration = document.querySelector("#duration").value;
let downPayment = document.querySelector("#down").value;
total = "";
interest = "";
duration = "";
downPayment = "";
});
You're not setting a value to the inputs, you're just over-writing the value of a varable:
total = "";
To set the value of the input, you'd set the .value property on the input:
document.getElementById("total").value = "";
For example:
const clearBtn = document.querySelector("#clearBtn");
clearBtn.addEventListener("click", function (e) {
document.getElementById("total").value = "";
});
<input type="number" id="total" />
<button id="clearBtn">Reset</button>
At a more generic level, you seem to be confused about the difference between these two things:
var total = document.getElementById("total").value;
total = "";
and:
var total = document.getElementById("total");
total.value = "";
In the first case the variable holds a copy of the value itself, and you're re-assigning the variable to a new value. This does nothing to the element.
But in the second case the variable holds a reference to the element, and you're updating a property on that element.

how can we display html form values as many times as the user insert them by pressing submit button each time?

<form action="#"></form>
<label for="First-name">First name: </label>
<input type="text" id="First-name" placeholder="Please insert fiid."><br>
<label for="Second-name">Second name: </label>
<input type="text" id="Second-name" placeholder="Please insert second name"> <br>
<label for="Passenger-weight">Passengers weight: </label>
<input type="number" class="weight" id ="Passenger-weight" placeholder="Please enter passengers weight"><br>
<label for="cargo-weight">cargo weight: </label>
<input type="number" class="weight" id ="cargo-weight" placeholder="Please enter cargo weight"><br>
<input type="submit" id ="submit" ><br>
</form>
<p id="sum"></p>
<div id="sumoftotal"></div>
<body>
<script language="JavaScript">
document.getElementById("submit").onclick=function (){
let firstName = document.getElementById("First-name").value;
let lastName= document.getElementById("Second-name").value;
let num1 = document.getElementById("Passenger-weight").value;
let num2 = document.getElementById("cargo-weight").value;
let total =parseInt(num1) + parseInt(num2);
document.getElementById("sum").innerHTML=(`${firstName} ${lastName} ${total }`)
}
</script>
</body>
my problem can be numbered:
number 1: when I press the submit button, input values show up, BUT when I want to insert a different data, the previous one disappear. I studied about it, because whatever comes in the function scope become local we cannot apply it outside, BUT I don't know how to change it.
number 2: I want to have the sum of total weights I insert at the end of my list, I know we can do this by loop, BUT I need something simpler and more preliminary because I am a novice and it would be a big jump for the time being.
all in all, I would be happy if anyone could help me.
Here is the primary and most basic approach.
var data = document.getElementById('data');
var weightElement = document.getElementById('total-weight');
document.getElementById("submit").onclick = function() {
/* Getting data */
let firstName = document.getElementById("First-name").value;
let lastName = document.getElementById("Second-name").value;
let num1 = document.getElementById("Passenger-weight").value;
let num2 = document.getElementById("cargo-weight").value;
let total = parseInt(num1) + parseInt(num2);
/* Appending element */
data.innerHTML = data.innerHTML + `First Name - ${firstName}, Last Name - ${lastName}, Weight - ${total} <br/>`;
weightElement.innerHTML = parseInt(weightElement.innerHTML) + total;
}
<body>
<form action="#"></form>
<label for="First-name">First name: </label>
<input type="text" id="First-name" placeholder="Please insert fiid."><br>
<label for="Second-name">Second name: </label>
<input type="text" id="Second-name" placeholder="Please insert second name"> <br>
<label for="Passenger-weight">Passengers weight: </label>
<input type="number" class="weight" id="Passenger-weight" placeholder="Please enter passengers weight"><br>
<label for="cargo-weight">cargo weight: </label>
<input type="number" class="weight" id="cargo-weight" placeholder="Please enter cargo weight"><br>
<input type="submit" id="submit"><br>
</form>
<div id="data"></div>
<div>Total weight = <span id="total-weight">0</span></div>
</body>

Add Two numbers from textbox using JavaScript

I was just trying to write a simple javascript program that will demonstrate to take user input from text field, and clicking the button will display the summation result of those number in a paragraph. But unfortunately the below code is not working. Clicking the button shows NAN in the Paragraph.
<input type="text" name="" id="num1"><br><br>
<input type="text" name="" id="num2"><br> <br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
<script>
let num1=parseInt(document.getElementById("num1"));
let num2=parseInt(document.getElementById("num2"));
let add=document.getElementById("add");
add.addEventListener("click",function(){
document.getElementById("para").innerHTML=num1+num2;
});
</script>
You are getting the elementById, but not getting that IDs value.
Add .value on the end of your getElementById
function addTogether()
{
var val1 = document.getElementById('val1').value;
var val2 = document.getElementById('val2').value;
var sum = parseInt(val1) + parseInt(val2);
console.log(sum);
}
<input type="text" id="val1" />
<input type="text" id="val2" />
<input type="button" value="Add Them Together" onclick="addTogether();" />
You can simply do it like this
<input type="text" id="num1"><br><br>
<input type="text" id="num2"><br><br>
<button id="add">Answer</button><br>
<p id="para"></p>
<script>
let add=document.getElementById("add");
add.addEventListener("click",function(){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var res = parseInt(num1) + parseInt(num2);
document.getElementById("para").innerHTML = res ;
});
</script>
here is the demo of working code
let add=document.getElementById("add");
add.addEventListener("click",function(){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var res = parseInt(num1) + parseInt(num2);
document.getElementById("para").innerHTML = res ;
});
<input type="text" id="num1"><br><br>
<input type="text" id="num2"><br><br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
you need to get the value of num1 and num2 and you need to get the value after you click -- so inside your function
<input type="text" name="" id="num1"><br><br>
<input type="text" name="" id="num2"><br> <br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
<script>
let add=document.getElementById("add");
add.addEventListener("click",function(){
let num1=parseInt(document.getElementById("num1").value);
let num2=parseInt(document.getElementById("num2").value);
document.getElementById("para").innerHTML=num1+num2;
});
</script>

I cannot get the javaScript to do the function i am requesting it to do, in my case multiply two values by a hidden and then add a final value

I am so lost as to why this is not working properly, as it is on similar previous code. This is for field personnel, a cheat Sheet to simply enter values and get a fast answer (calculation). They enter the value of Num5/6/7 code multiplies 3 values one hidden then adds the last value together and upon click button the result is shown.
Here is my code (taken from copy/paste of a working conversion).
<div class="containerHydro">
<p>
<label >Fluid Column Length</label>
<input type="number" id="num5">
<label >Fluid Weight</label>
<input type="number" id="num6">
<label >Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()"/>
</p>
<p id="total1"></p>
</div>
The Function also copy/paste of multiply two int then divide by hidden (which works BTW)
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt('numSvn');
var p =document.getElementById('total1');
p.innerHTML += total1;
}
Here is the same idea which works fine-
Code-
<div class="container7">
<p>
<label id="H2S Percent">H2S Percentage</label>
<input id="num3" type="number" name="num3" placeholder="H2S Percent">
<label id="H2S Percent">WHP</label>
<input id="num4" type="number" name="num4"placeholder="Well Head Pressure" > <br>
</p>
<input type="button" value="H2S Partial Pressure" onclick="math()"/>
<p id="result"></p>
</div>
Function
function math() {
var numThree = document.getElementById('num3').value;
var numFour = document.getElementById('num4').value;
var result = parseInt(numThree) * parseInt(numFour) / 1000000;
var p = document.getElementById('result');
p.innerHTML += result;
}
function calculate() {
var numFive = document.getElementById('num5').value;
var numSix = document.getElementById('num6').value;
var numSvn = document.getElementById('num7').value;
var total1 = parseInt(numFive) * parseInt(numSix) * 0.052 + parseInt(numSvn);
var p = document.getElementById('total1');
p.innerHTML += total1;
}
input {
display: block;
}
<div class="containerHydro">
<p>
<label>Fluid Column Length</label>
<input type="number" id="num5">
<label>Fluid Weight</label>
<input type="number" id="num6">
<label>Well Head Pressure</label>
<input type="number" id="num7">
<p>
<input type="button" value="Sum" onclick="calculate()" />
</p>
<p id="total1"></p>
</div>

adding multiplied numbers using javascript

function multiplyBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num3= document.getElementById("result").value = num1 * num2;
document.getElementById("total").value = +num3 ;
}
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
<p>Total :<br>
<input type="text" name="total" id="total" value=""/>
</p>
function multiplyBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num3= document.getElementById("result").value = num1 * num2;
}
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
I am multiplying two numbers here.how to add those multiplied numbers in another text box.suppose 2&5 are multiplied later 4&6 multiplied how to add those numbers.
Try this. You need to parse the input value using parseFloat. This will convert the string to a number. The existing result value is added to the newly calculating value. |0 is used for the false value of input getting 0
Updated
prev, present and total result box were added
Append each additional input with new result.
var last=0;
function multiplyBy() {
var num1 = document.getElementById("firstNumber");
var num2 = document.getElementById("secondNumber");
var prev = document.getElementById("prev");
var present = document.getElementById("present");
var total = document.getElementById("result");
prev.value=last;
present.value=(parseFloat(num1.value) * parseFloat(num2.value))
last = last+(parseFloat(num1.value) * parseFloat(num2.value))
total.value=last;
num1.value = "";
num2.value = "";
}
1st Number : <input type="text" id="firstNumber" value="" /><br> 2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p >
Prev result:<br>
<input type="text" name="result" id="prev" ><br>
Present:<br>
<input type="text" name="result" id="present" ><br>
The total Result is : <br>
<input type="text" name="result" id="result"><br>
</p>
You just need for get value of text box and add it with result
function multiplyBy()
{ var sum = 0;
var num=0;
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num =parseInt(num1 * num2);
num3=parseInt(document.getElementById("result").value);
document.getElementById("result").value=(num + num3);
}
</script>
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value="0"/>
</p>
I have added the multiplyBy() to both the input fields and changed the type to number to restrict the user to enter number only.
Please check the code snippet below.
document.getElementById("firstNumber").addEventListener("change",multiplyBy);
document.getElementById("secondNumber").addEventListener("change",multiplyBy);
function multiplyBy()
{
actualResult = document.getElementById("actualResult").value ? document.getElementById("actualResult").value : 0; // Return zero if there is no value in actualResult input field
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num3= document.getElementById("result").value = num1 * num2;
document.getElementById("actualResult").value = Number(actualResult) + num3;
}
1st Number : <input type="number" id="firstNumber" value=""/><br>
2nd Number: <input type="number" id="secondNumber" value=""/><br>
<p>The Current Result is : <br>
<input type="number" name="result" id = "result" value=""/>
</p>
<p>Previous Result + Current Result : <br>
<input type="number" name="actualResult" id = "actualResult" value=""/>
</p>
You need to add event handlers if you want to calculate on change of textbox input like following.
function multiplyBy()
{
var result = document.getElementById("result");
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
var num3= parseFloat(num1) * parseFloat(num2);// to convert entered values to float and || 0 to use 0 if no value is there
if(!isNaN(num3)){
document.getElementById("resultPrev").value = document.getElementById("result").value;
document.getElementById("resultCurrent").value = num3;
result.value = parseFloat(result.value || 0) + num3;
}
}
document.getElementById("firstNumber").addEventListener("change",multiplyBy);
document.getElementById("secondNumber").addEventListener("change",multiplyBy);
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" /><br>
<p>The Previous Result is : <br>
<input type="text" name="resultPrev" id = "resultPrev" value="0"/>
</p>
<p>The Current Result is : <br>
<input type="text" name="resultCurrent" id = "resultCurrent" value=""/>
</p>
<p>The Final Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
Consider handling non number values.

Categories

Resources