Performing arithmetic operations on two inputs in JavaScript - javascript

I am trying to add two numbers that a user enters, and returning the sum, difference, product or the quotient of two values the user enters. For that, I made two inputs with a drop-down list between that. The drop down list has options to add, subtract, multiply and divide. What I am trying to do is perform the operation the user attempts to perform. You can see a demo here.
//Variables
let firstNum = document.getElementById("num1");
let secondNum = document.getElementById("num2");
let result = document.getElementById("result");
//Event Listeners
firstNum.addEventListener("input", mainFunction());
secondNum.addEventListener("input", mainFunction());
result.addEventListener("input", mainFunction());
//Main JavaScript
function mainFunction() {
if (document.getElementById("options").options[0]) {
var one = parseFloat(firstNum.value) || 0;
var two = parseFloat(secondNum.value) || 0;
result.innerHTML = one+two;
}
}
* {
font-family: helvetica;
text-align: center;
}
<h1>Calculator</h1>
<form>
<input type="number" id="num1" placeholder="First Number"/>
<select id="options">
<option id="addition">+</option>
<option id="subtraction">−</option>
<option id="multiplication">✖</option>
<option id="division">÷</option>
</select>
<input type="number" id="num2" placeholder="Second Number"/>
<p id="result"></p>
</form>
Please inform me if you find any errors.
Thanks.

I have changed your code, the new version is here http://jsfiddle.net/v56fkaww/6/
The error was that you should encapsulate the call of function into an anonymous function
//Event Listeners
firstNum.addEventListener("input",function(){mainFunction()});
secondNum.addEventListener("input",function(){mainFunction()});

Everything seems to be fine except for a small problem :
firstNum.addEventListener("input", mainFunction());
should be :
firstNum.addEventListener("input", mainFunction);
Since the function is already defined and this expects a function so you only need to pass a reference to the function.
Code :
I added functionality for all four operators and shortened the code a bit
//Variables
let firstNum = document.getElementById("num1"),
secondNum = document.getElementById("num2"),
result = document.getElementById("result");
//Event Listeners
firstNum.addEventListener("input", mainFunction);
secondNum.addEventListener("input", mainFunction);
result.addEventListener("input", mainFunction);
//Main JavaScript
function mainFunction() {
var one = +firstNum.value||0; // convert to number
var two = +secondNum.value||0; // convert to number
var opt = document.getElementById("options");
// this is the shorter than what you are using
result.innerHTML = opt.options[0] ? one + two : opt.options[1] ? one - two : opt.options[2] ? one * two : one / two;
}
* {
font-family: helvetica;
text-align: center;
}
<h1>Calculator</h1>
<form>
<input type="number" id="num1" placeholder="First Number"/>
<select id="options">
<option id="addition">+</option>
<option id="subtraction">−</option>
<option id="multiplication">✖</option>
<option id="division">÷</option>
</select>
<input type="number" id="num2" placeholder="Second Number"/>
<p id="result"></p>
</form>

There is also a non standard way to evaluate operator without the need of performing a switch or if , this is using a Function constructor and execute inmediate. result.innerHTML = (new Function("return "+one+operator+two))();
//Variables
let firstNum = document.getElementById("num1");
let secondNum = document.getElementById("num2");
let result = document.getElementById("result");
let operator = document.getElementById("options").value;
//Event Listeners
//You should asign the function itself not the result like mainFunction()
firstNum.addEventListener("input", mainFunction);
secondNum.addEventListener("input", mainFunction);
result.addEventListener("input", mainFunction);
//All of this is like something.addEventListener("input", function(){//code});
function mainFunction() {
var one = parseFloat(firstNum.value) || 0;
var two = parseFloat(secondNum.value) || 0;
//evaluate the operator as a javascipt operator not just as string
result.innerHTML = (new Function("return "+one+operator+two))();
}

<td><input type="number" class="form-control text-center tot" id="input1"></td>
<td id="mark" class="text-center"></td>
<td><input type="number" class="form-control text-center tot" id="input2"></td>
<td id="total" class="text-center"></td>
function inputOper(operaterName) {
let input1 = Number($('#input1').val());
let input2 = Number($('#input2').val());
let result = $('#total');
if(operaterName == 'add'){
result = input1 + input2;
$('#mark').html('+');
}else if(operaterName == 'sub'){
result = input1 - input2;
$('#mark').html('-');
}else if(operaterName == 'mul'){
result = input1 * input2;
$('#mark').html('*');
}else if(operaterName == 'div'){
result = (input1 / input2).toFixed(2);
$('#mark').html('/');
}
$('#total').html(result)
}

Related

Javascript: Calculation of the amount when changing the value of the third input

I have three fields that are calculated: coef, cost of materials, and manufacturing cost.
First, calculate its coef * cost of materials, result in manufacturing cost input.
The calculation of the total amount is the cost of materials * manufacturing cost, but I need the ability to change the amount of Manufacturing cost and get the total result
How to do this?
My code:
function sum(el) {
let coefEl = document.getElementById('coef');
let entrPriceEl = document.getElementById('enterence_price');
let extraEl = document.getElementById('extra');
let priceEl = document.getElementById('price');
let extraresultEl;
let result;
if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
extraextraresultEl = parseFloat(coefEl.value) * parseFloat(entrPriceEl.value);
extraEl.value = extraextraresultEl;
result = (parseFloat(entrPriceEl.value) * parseFloat(coefEl.value) + parseFloat(extraEl.value));
if (!isNaN(result)) {
priceEl.value = result.toFixed(2);
}
} else if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
result = parseFloat(entrPriceEl.value) * parseFloat(extraEl.value);
if (!isNaN(result)) {
priceEl.value = result;
}
}
}
<label>Coefficient<br></label>
<input type="text" value="2" id="coef" onkeyup="sum(this);">
<br>
<label>The cost of materials<br></label>
<input type="text" value="2000" id="enterence_price" onkeyup="sum(this);">
<br>
<label>Manufacturing cost<br></label>
<input type="text" id="extra" onkeyup="sum(this);">
<br>
<label>Sum<br></label>
<input type="text" id="price" onkeyup="sum(this);">
<br>
You need to apply a different function on mf cost input, because if you will use the same function, it will never let you alter the value, because its value also getting generated from the same function you write for above 2 values
if you need something else, pls feel free to comment
let coefEl = document.getElementById('coef');
let entrPriceEl = document.getElementById('enterence_price');
let extraEl = document.getElementById('extra');
let priceEl = document.getElementById('price');
function sum(el) {
let extraresultEl;
if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
extraextraresultEl = parseFloat(coefEl.value) * parseFloat(entrPriceEl.value);
extraEl.value = extraextraresultEl;
result = (parseFloat(entrPriceEl.value) * parseFloat(coefEl.value) + parseFloat(extraEl.value));
if (!isNaN(result)) {
priceEl.value = result.toFixed(2);
}
} else if (el.id === "enterence_price" || el.id === "extra" || el.id === "coef") {
result = parseFloat(entrPriceEl.value) * parseFloat(extraEl.value);
if (!isNaN(result)) {
priceEl.value = result;
}
}
}
function canBeChnaged(el){
var coefVal = parseInt(coefEl.value);
var costofMatVal = parseInt(entrPriceEl.value);
var mfCostVal = parseInt(extraEl.value);
var finalSum = (coefVal * costofMatVal) + mfCostVal;
priceEl.value = finalSum.toFixed(2);
}
<label>Coefficient<br></label>
<input type="text" value="2" id="coef" onkeyup="sum(this);">
<br>
<label>The cost of materials<br></label>
<input type="text" value="2000" id="enterence_price" onkeyup="sum(this);">
<br>
<label>Manufacturing cost<br></label>
<input type="text" id="extra" onkeyup="canBeChnaged(this);">
<br>
<label>Sum<br></label>
<input type="text" id="price" onkeyup="sum(this);">
<br>
A more succinct way is to is to wrap everything into a <form> then listen for the input event. The input event will trigger a call to an event handler (in the example below it is function calc(e)) whenever the user enters data in a form control (in this case all <input>s of <form>). Use properties of HTML elements like type and step to control and validate user input. References to previously mentioned topics are located after the example below.
Details are commented in example below
// Register the <form>
const form = document.forms[0];
// Register all form controls of <form>
// In this case all <input> and <output>
const data = form.elements;
// Run function calc() if any valid user input is entered in <form>
form.oninput = calc;
// Pass the event
function calc(e) {
// Convert any valid user input of the <input>s into a real number
const c = parseFloat(data.cof.value);
const m = parseFloat(data.mat.value);
const l = parseFloat(data.lab.value);
// Reference the <output>
const s = data.sum;
// Realistic formula
const t = (c * m) + l;
// Display the value of output as the result of formula
s.value = t.toFixed(2);
}
:root,
input,
output {
font: 400 6vh/10vh Consolas;
}
label,
input,
output {
display: inline-block;
}
label {
width: 9ch;
}
input,
output {
height: 1.5ch;
width: 12ch;
text-align: right;
}
#cof {
width: 6ch;
text-align: center;
color: blue;
}
<form>
<label>Markup</label>
<input id="cof" type="number" value="2">
<br>
<label>Materials</label>
<input id='mat' type="number" value="0.00" step=".01">
<br>
<label>Labor</label>
<input id='lab' type="number" value='0.00' step=".01">
<hr>
<label>Total: </label>
<output id='sum'>0.00</output>
</form>
Reference
HTMLFormControlCollection
HTMLFormElement
<input> Element

Auto substract both values from 100

I created two input fields where they should substract from each other keeping a max value at 100.
Currently it substracted value is shown in the second value. I want it to be interchangeable. Irrespective of whether I put in first or second input field, the answer shows in the other.
Could someone help?
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
var val1 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val1) { val1 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val1;
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue()">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue()">
</div>
The simple way to achieve this would be to group the inputs by class and attach a single event handler to them. Then you can take the entered value from 100, and set the result to the field which was not interacted with by the user. To do that in jQuery is trivial:
$('.updatedue').on('input', function() {
var total = parseInt($('#totalval').val(), 10) || 0;
var subtracted = total - (parseInt(this.value, 10) || 0);
$('.updatedue').not(this).val(subtracted);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" id="totalval" name="totalval" value="100" />
<div>
Enter Value:
<input type="text" name="inideposit" class="updatedue form-control" id="inideposit" />
</div>
<div>
Subtracted:
<input type="text" name="remainingval" class="updatedue form-control" id="remainingval" />
</div>
You can easily validate this so that outputs < 0 and > 100 can be discounted, if required.
Edit your code as below
function updateDue(box) {
var total = parseInt(document.getElementById("totalval").value);
if(box == 1){
var val = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val;
}else if(box == 2){
var val = parseInt(document.getElementById("remainingval").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val) { val = 0; }
var ansD = document.getElementById("inideposit");
ansD.value = total - val;
}
}
<input type="hidden" id="totalval" name="totalval" value="100" onchange="updateDue(0)">
<div>
Enter Value:
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue(1)">
</div>
<div>
Substracted:
<input type="text" name="remainingval" class="form-control" id="remainingval" onchange="updateDue(2)">
</div>

Javascript, Chrome don't recognise the variable outside the function

I hope you are well!!
Recently I created this calculator following a tutorial on youtube.
How you can see below I put all the variable outside the function.
In Firefox is working fine, but if I use Google Chrome and I try to use it, is giving me the result of NaN..... I fixed this error moving the var inside the function, but I don't understand why with Chrome I have to move it inside and Firefox no....
If anyone would be able to give me an explanation I will really appreciate!
Thanks!!!!
var value1 = parseInt(document.querySelector("#textbox1").value);
var value2 = parseInt(document.querySelector("#textbox2").value);
var operator = document.querySelector("#operators").value;
var total = document.getElementById("total");
var calculate;
function result() {
if (operator === "add") {
calculate = value1 + value2;
} else if (operator === "sub") {
calculate = value1 - value2;
} else if (operator === "multiply") {
calculate = value1 * value2;
} else if (operator === "divide") {
calculate = value1 / value2;
}
total.innerHTML = calculate;
}
<form>
<input type="text" id="textbox1">
<input type="text" id="textbox2"><br>
<select id="operators">
<option value="add">Add</option>
<option value="sub">Sub</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="button" id="confirm" value="Result" onclick="result()">
<div id="total"></div>
</form>
The problem is you're grabbing the values before the user fills them in, right away, when the page loads. (You've said it's "working" in Firefox. It doesn't for me, but if you have autofill enabled, it may be filling in values from a previous run.)
Instead, grab the values within the result function:
var total = document.getElementById("total");
function result() {
var value1 = parseInt(document.querySelector("#textbox1").value);
var value2 = parseInt(document.querySelector("#textbox2").value);
var operator = document.querySelector("#operators").value;
var calculate;
if (operator === "add") {
calculate = value1 + value2;
} else if (operator === "sub") {
calculate = value1 - value2;
} else if (operator === "multiply") {
calculate = value1 * value2;
} else if (operator === "divide") {
calculate = value1 / value2;
}
total.innerHTML = calculate;
}
<form>
<input type="text" id="textbox1">
<input type="text" id="textbox2"><br>
<select id="operators">
<option value="add">Add</option>
<option value="sub">Sub</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="button" id="confirm" value="Result" onclick="result()">
<div id="total"></div>
</form>

JS instant output to HTML

I want to get input from user, multiply it by 1.3 for example and output to window instantly, like as user types function is executing and displaying in it in HTML instantly. How do it do it?
Here my code
function calc() {
amount = document.getElementById("amount").value;
num2 = 1.3;
document.getElementById("result").innerHTML = amount * num2;
return result;
}
<input id='amount', type="text" >
<button onclick="calc()"> Buy Now! </button>
<p> Result is: <br>
<span id = "result"> </span>
<input type="text"onkeyup="calc()">
First off, you got some invalid HTML:
What's that comma?
<input id='amount', type="text" >
Attributes don't need any separator — just put a space:
<input id='amount' type="text" >
Getting rid of pointless spaces, a cleaner HTML fragment follows:
<input id='amount' type="text">
<button onclick="calc()">Buy Now!</button>
<p>Result is:<br>
<span id="result"></span>
Now, let's try to list some options:
The keydown and keypress events won't work because they're fired before value changes.
The keyup event, as suggested #Dmitri Usanov, will work only partially: it is called when the key releases (not as soon as the text is updated) and if you e.g. paste by right-clicking then it won't fire.
The input is the solution. Note that it requires HTML5.
Working demo:
function calc() {
// Let's convert the input text to a number.
const amount = +document.getElementById("amount").value;
// The number to multiply by.
const num2 = 1.3;
// The number of decimal places we wish to truncate at.
const precision = 2;
const scale = 10 ** precision;
return Math.round(amount * num2 * scale) / scale;
}
window.addEventListener("load", () => {
const outputSpan = document.getElementById("result");
document.getElementById("amount").addEventListener("input", () => {
outputSpan.innerHTML = calc(this.value);
});
});
<input id='amount' type="text">
<button onclick="calc()">Buy Now!</button>
<p>Result is:<br>
<span id="result"></span>
Try this
function calc(isEsc) {
const num2 = 1.3;
let result = document.getElementById("result"),
amount = document.getElementById("amount");
if (isEsc) {
result.innerHTML = 0;
amount.value = '';
} else {
result.innerHTML = amount.value * num2;
}
}
document.onkeyup = function(evt) {
evt = evt || window.event;
var isEscape = false;
if ("key" in evt) {
isEscape = (evt.key == "Escape" || evt.key == "Esc");
} else {
isEscape = (evt.keyCode == 27);
}
calc(isEscape);
};
<input type="text" id="amount" />
<span id="result">0</span>

Result is not showing

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var result = document.getElementById('answer').value;
if (document.getElementById('add')) {
function myFunction() {
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
ans = (parseInt(add1)+parseInt(add2));
result.innerHTML = ans;
}
}
</script>
</head>
<body>
<input type="text" id="num1" />
<select id="problem">
<option id="add">+</option>
<option id="sub">-</option>
<option id="mul">x</option>
<option id="div">÷</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
</body>
</html>
I'm trying to make a sum solver by taking the values from the two text boxes and after clicking the button, it should post the result in the text box below. However it is not doing that.
I also want the program to change how a problem is solved using the dropdown menu with the mathematical symbols.
Thanks.
I think you're after something like this
function myFunction() {
var result = document.getElementById('answer'),
operator = document.getElementById('problem').value,
add1 = document.getElementById('num1').value,
add2 = document.getElementById('num2').value,
ans = 0;
switch (operator) {
case '+':
ans = (parseInt(add1) + parseInt(add2));
break;
case '-':
ans = (parseInt(add1) - parseInt(add2));
break;
case 'x':
ans = (parseInt(add1) * parseInt(add2));
break;
case '÷':
ans = (parseInt(add1) / parseInt(add2));
break;
}
result.value = ans;
}
instead of using if statements, and creating different functions, just have one function and determine the operand.
Edit: Also, watch out for your variable declarations. 'ans', 'add1' and 'add2' weren't being declared which resulted in global variables being created
The problem should be with the line
var result = document.getElementById('answer').value;
Try the below snippet
var result=document.getElementById('answer');
ans = (parseInt(add1)+parseInt(add2));
result.value=ans;
http://jsfiddle.net/2W5za/1/
You have a few issues. Not sure what you were going for with the if but remove it. Also, set the value of a textbox with value not innerHTML.
function myFunction() {
var result = document.getElementById('answer');
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
ans = (parseInt(add1)+parseInt(add2));
result.value = ans;
}
http://jsfiddle.net/LjqMJ/
Regarding the first part of the question (and that for which this question is titled), one problem I see is this line of code right here:
var result = document.getElementById('answer').value;
What is the type of result? Later on you treat it as if it is a DOMElement with result.innerHTML = ans; by assuming it has a property innerHTML. However because you used .value it's in fact a string which will not have innerHTML.
Regarding the second part, you can assert which function is selected in the <select> by looking at it's .value. The <option> tags will always exist, regardless of if they are selected or not.
Speaking more broadly, I highly recommend you check out using the debugger in either chrome or firefox. That will allow you to drop a breakpoint in your code, and figure out if the value is being computed correctly, and see what it is attempting to write to, all interactively.
Chrome:
https://developers.google.com/chrome-developer-tools/docs/javascript-debugging
Firefox:
https://developer.mozilla.org/en-US/docs/Tools/Debugger
<!DOCTYPE html>
<html>
<head></head>
<body>
<input type="text" id="num1" />
<select id="problem">
<option value="add">+</option>
<option value="sub">-</option>
<option value="mul">x</option>
<option value="div">%</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
<script type="text/javascript">
function myFunction()
{
var e = document.getElementById("problem");
var sOperation = e.options[e.selectedIndex].value;
add1 = document.getElementById('num1').value;
add2 = document.getElementById('num2').value;
var ans;
if (!isNaN(add1) && !isNaN(add2)){
if(sOperation=='add'){
//Add
ans = parseInt(add1)+parseInt(add2);
} else if (sOperation=='sub') {
//Subtract
ans = parseInt(add1)-parseInt(add2);
} else if (sOperation=='mul') {
//Multiple
ans = parseInt(add1) * parseInt(add2);
} else if (sOperation=='div') {
//Divide
ans = parseInt(add1) / parseInt(add2);
}
document.getElementById("answer").value = ans;
} else {
alert("Please enter numeric values only");
return false;
}
}
There are many things wrong with your code. However, to fix your problem, change = ans to = ans.toString();
You see, in javascript integers and strings cannot change to each other's values without a conversion (kind of like a brother and sister refusing to share), so toString() is used for a conversion to String.
The other thing to change is innerHTML to value, because you are dealing with text boxes.
HTML
<input type="text" id="num1" />
<select id="problem">
<option id="add">+</option>
<option id="sub">-</option>
<option id="mul">x</option>
<option id="div">÷</option>
</select>
<input type="text" id="num2" />
<br />
<input type="submit" onclick="myFunction();" />
<br />
<input type="text" id="answer" readonly />
JavaScript
function myFunction() {
var result = document.getElementById('answer');
var operator = document.getElementById('problem').value;
var add1 = document.getElementById('num1').value;
var add2 = document.getElementById('num2').value;
var ans;
if (!isNaN(add1) && !isNaN(add2)) {
//Addition
if (operator == '+')
{
ans = (parseInt(add1) + parseInt(add2));
}
//Subtraction
else if (operator == '-') {
ans = (parseInt(add1) - parseInt(add2));
}
//Multiplication
else if (operator == 'x') {
ans = (parseInt(add1) * parseInt(add2));
}
//Division
else if (operator == '÷') {
ans = (parseInt(add1) / parseInt(add2));
}
//Result
result.value = ans;
} else {
alert("Please enter numeric values only");
return false;
}
}
Fiddle Demo

Categories