Calculator giving wrong results in JS
i'm learning some javascript and i tried to make a simple calculator.
The sum worked just fine, but the rest of the operations didnt work. What i'm doing wrong?
js:
function soma()
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
if(document.getElementById("btnSoma").onclick)
var soma = s1 + s2;
document.getElementById("resultado").innerHTML = soma;
else if(document.getElementById("btnSubtrair").onclick)
var subtrair = s1 - s2;
document.getElementById("resultado").innerHTML = subtrair;
else if(document.getElementById("btnMultiplicar").onclick)
var mult = s1 * s2;
document.getElementById("resultado").innerHTML = mult;
else if(document.getElementById("btnDividir").onclick)
var div = s1 / s2;
document.getElementById("resultado").innerHTML = div;
JSFiddle link: https://jsfiddle.net/y7r1m4nx/ with HTML
Also, can someone please explain why i have to put the ,10 in parseInt? i didnt understand it very well from Mozilla docs.
javascript html
add a comment |
i'm learning some javascript and i tried to make a simple calculator.
The sum worked just fine, but the rest of the operations didnt work. What i'm doing wrong?
js:
function soma()
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
if(document.getElementById("btnSoma").onclick)
var soma = s1 + s2;
document.getElementById("resultado").innerHTML = soma;
else if(document.getElementById("btnSubtrair").onclick)
var subtrair = s1 - s2;
document.getElementById("resultado").innerHTML = subtrair;
else if(document.getElementById("btnMultiplicar").onclick)
var mult = s1 * s2;
document.getElementById("resultado").innerHTML = mult;
else if(document.getElementById("btnDividir").onclick)
var div = s1 / s2;
document.getElementById("resultado").innerHTML = div;
JSFiddle link: https://jsfiddle.net/y7r1m4nx/ with HTML
Also, can someone please explain why i have to put the ,10 in parseInt? i didnt understand it very well from Mozilla docs.
javascript html
3
document.getElementById("btnMultiplicar").onclick
is an event handler. It's a function that fires when the button with that ID is clicked. You can't use it in the manner that you have. In regards toparseInt
: thevalue
property is astring
. If you add two strings"5" + "5"
, it's"55"
. If you add two numbers5 + 5
, it's10
.parseInt
changes"5"
to5
, for example.
– Tyler Roper
Nov 12 at 20:48
add a comment |
i'm learning some javascript and i tried to make a simple calculator.
The sum worked just fine, but the rest of the operations didnt work. What i'm doing wrong?
js:
function soma()
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
if(document.getElementById("btnSoma").onclick)
var soma = s1 + s2;
document.getElementById("resultado").innerHTML = soma;
else if(document.getElementById("btnSubtrair").onclick)
var subtrair = s1 - s2;
document.getElementById("resultado").innerHTML = subtrair;
else if(document.getElementById("btnMultiplicar").onclick)
var mult = s1 * s2;
document.getElementById("resultado").innerHTML = mult;
else if(document.getElementById("btnDividir").onclick)
var div = s1 / s2;
document.getElementById("resultado").innerHTML = div;
JSFiddle link: https://jsfiddle.net/y7r1m4nx/ with HTML
Also, can someone please explain why i have to put the ,10 in parseInt? i didnt understand it very well from Mozilla docs.
javascript html
i'm learning some javascript and i tried to make a simple calculator.
The sum worked just fine, but the rest of the operations didnt work. What i'm doing wrong?
js:
function soma()
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
if(document.getElementById("btnSoma").onclick)
var soma = s1 + s2;
document.getElementById("resultado").innerHTML = soma;
else if(document.getElementById("btnSubtrair").onclick)
var subtrair = s1 - s2;
document.getElementById("resultado").innerHTML = subtrair;
else if(document.getElementById("btnMultiplicar").onclick)
var mult = s1 * s2;
document.getElementById("resultado").innerHTML = mult;
else if(document.getElementById("btnDividir").onclick)
var div = s1 / s2;
document.getElementById("resultado").innerHTML = div;
JSFiddle link: https://jsfiddle.net/y7r1m4nx/ with HTML
Also, can someone please explain why i have to put the ,10 in parseInt? i didnt understand it very well from Mozilla docs.
javascript html
javascript html
asked Nov 12 at 20:45
César N.
536
536
3
document.getElementById("btnMultiplicar").onclick
is an event handler. It's a function that fires when the button with that ID is clicked. You can't use it in the manner that you have. In regards toparseInt
: thevalue
property is astring
. If you add two strings"5" + "5"
, it's"55"
. If you add two numbers5 + 5
, it's10
.parseInt
changes"5"
to5
, for example.
– Tyler Roper
Nov 12 at 20:48
add a comment |
3
document.getElementById("btnMultiplicar").onclick
is an event handler. It's a function that fires when the button with that ID is clicked. You can't use it in the manner that you have. In regards toparseInt
: thevalue
property is astring
. If you add two strings"5" + "5"
, it's"55"
. If you add two numbers5 + 5
, it's10
.parseInt
changes"5"
to5
, for example.
– Tyler Roper
Nov 12 at 20:48
3
3
document.getElementById("btnMultiplicar").onclick
is an event handler. It's a function that fires when the button with that ID is clicked. You can't use it in the manner that you have. In regards to parseInt
: the value
property is a string
. If you add two strings "5" + "5"
, it's "55"
. If you add two numbers 5 + 5
, it's 10
. parseInt
changes "5"
to 5
, for example.– Tyler Roper
Nov 12 at 20:48
document.getElementById("btnMultiplicar").onclick
is an event handler. It's a function that fires when the button with that ID is clicked. You can't use it in the manner that you have. In regards to parseInt
: the value
property is a string
. If you add two strings "5" + "5"
, it's "55"
. If you add two numbers 5 + 5
, it's 10
. parseInt
changes "5"
to 5
, for example.– Tyler Roper
Nov 12 at 20:48
add a comment |
3 Answers
3
active
oldest
votes
Here is the code working:
function soma(type)
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
var result;
if (type === '+')
result = s1 + s2;
else if (type === '-')
result = s1 - s2;
else if(type === '*')
result = s1 * s2;
else if(type === '/')
result = s1 / s2;
document.getElementById("resultado").innerHTML = result;
<div class="container text-center">
<input name="Valor 1" id="valor1">
<input name="Valor 2" id="valor2"><br>
<button type="submit" onclick="soma('+')" id="btnSoma">Somar</button><br>
<button type="submit" onclick="soma('-')" id="btnSubtrair">Subtrair</button><br>
<button type="submit" onclick="soma('/')" id="btnDividir">Dividir</button><br>
<button type="submit" onclick="soma('*')" id="btnMultiplicar">Multiplicar</button><br>
<p id="resultado">Resultado</p>
</div>
You can't look at the element to see which was clicked.
if(document.getElementById("btnSoma").onclick)
Instead you can pass in some value you can use to determine the action. In teh example code I am passing in a parameter to indicate the action I want to happen:
Add:'+', Subract:'-', Multiply:'*' and divide:'/'
There are other ways to accomplish this, including having each onclick
call a different function.
But this should help.
Sorry, i'm late. Thanks for your help, now its working!
– César N.
Nov 19 at 18:12
add a comment |
You should set up your javascript where
document.getElementById("btnSoma").click(function()
var add = s1 + s2;
document.getElementById("resultado").innerHTML = add;
);
and repeat this for mult, div, subtraction as desired. You do not need to call soma() as an onclick function with this implementation.
Also, the javascript parseInt
function can take two parameters, the value to parse and the radix
which is what base you are processing numbers in. Typically we count in base 10, but some programs may use different bases.
add a comment |
Well, your if statement is incorrect. You are actually only checking if onClick
was defined on your button that you retrieve.
As it has been defined, you will always end up in the first if-block, so you will never really do something else but sums. It is just an eventhandler to indicate what the program would do when you actually click it, which you forward to the soma()
function.
Now, I don't speak the language you seem to be speaking, so having this question be in English, would be helpful, but I am thinking that soma means sum?
If that is the case, you could make as a starting point 4 different functions, that handle the same input, but perform different operations, something like
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" onclick="sum()">Sum</button><br>
<button type="button" onclick="subtract()">Subtract</button><br>
<button type="button" onclick="multiply()">Multiply</button><br>
<button type="button" onclick="divide()">Divide</button><br>
<span id="result"></span>
This would be the easiest version to transform in. Nowadays, people really don't use the onclick
syntax inside html anymore, so you would now rather attach an event inside your javascript, and let it get handled there, for example
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.getElementById('btnSum').addEventListener('click', sum);
document.getElementById('btnSubtract').addEventListener('click', subtract);
document.getElementById('btnDivide').addEventListener('click', divide);
document.getElementById('btnMultiply').addEventListener('click', multiply);
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" id="btnSum">Sum</button><br>
<button type="button" id="btnSubtract">Subtract</button><br>
<button type="button" id="btnMultiply">Multiply</button><br>
<button type="button" id="btnDivide">Divide</button><br>
<span id="result"></span>
This in total doesn't bring a lot, but you could of course change the html slightly to allow for all operators to be handled, and where it finally gets a bit more interesting, because you can finally use the event argument
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.querySelectorAll('[data-operator]').forEach( btn => btn.addEventListener( 'click', calculate ) );
function calculate( eventSource )
const operator = eventSource.target.getAttribute('data-operator');
if (!operator)
return;
// eval should be used carefully here, but it is just demonstrating what you could get to
output
.innerText = eval( `($parseInt(value1.value)) $operator ($parseInt(value2.value))` );
<input id="value1">
<input id="value2"><br>
<button type="button" data-operator="+">Sum</button><br>
<button type="button" data-operator="-">Subtract</button><br>
<button type="button" data-operator="*">Multiply</button><br>
<button type="button" data-operator="/">Divide</button><br>
<span id="result"></span>
Now, for the parseInt, the second argument would be the base, for example
console.log( parseInt( '11', 2 ) ); // input is in binairy format
console.log( parseInt( '11', 10 ) );// input is in decimal format
console.log( parseInt( '11', 16 ) );// input is in hexadecimal format
Sorry, it was overly long, I just wanted to give a step by step example on how you can change your code going forward :(
– Icepickle
Nov 12 at 21:17
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269842%2fcalculator-giving-wrong-results-in-js%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
Here is the code working:
function soma(type)
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
var result;
if (type === '+')
result = s1 + s2;
else if (type === '-')
result = s1 - s2;
else if(type === '*')
result = s1 * s2;
else if(type === '/')
result = s1 / s2;
document.getElementById("resultado").innerHTML = result;
<div class="container text-center">
<input name="Valor 1" id="valor1">
<input name="Valor 2" id="valor2"><br>
<button type="submit" onclick="soma('+')" id="btnSoma">Somar</button><br>
<button type="submit" onclick="soma('-')" id="btnSubtrair">Subtrair</button><br>
<button type="submit" onclick="soma('/')" id="btnDividir">Dividir</button><br>
<button type="submit" onclick="soma('*')" id="btnMultiplicar">Multiplicar</button><br>
<p id="resultado">Resultado</p>
</div>
You can't look at the element to see which was clicked.
if(document.getElementById("btnSoma").onclick)
Instead you can pass in some value you can use to determine the action. In teh example code I am passing in a parameter to indicate the action I want to happen:
Add:'+', Subract:'-', Multiply:'*' and divide:'/'
There are other ways to accomplish this, including having each onclick
call a different function.
But this should help.
Sorry, i'm late. Thanks for your help, now its working!
– César N.
Nov 19 at 18:12
add a comment |
Here is the code working:
function soma(type)
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
var result;
if (type === '+')
result = s1 + s2;
else if (type === '-')
result = s1 - s2;
else if(type === '*')
result = s1 * s2;
else if(type === '/')
result = s1 / s2;
document.getElementById("resultado").innerHTML = result;
<div class="container text-center">
<input name="Valor 1" id="valor1">
<input name="Valor 2" id="valor2"><br>
<button type="submit" onclick="soma('+')" id="btnSoma">Somar</button><br>
<button type="submit" onclick="soma('-')" id="btnSubtrair">Subtrair</button><br>
<button type="submit" onclick="soma('/')" id="btnDividir">Dividir</button><br>
<button type="submit" onclick="soma('*')" id="btnMultiplicar">Multiplicar</button><br>
<p id="resultado">Resultado</p>
</div>
You can't look at the element to see which was clicked.
if(document.getElementById("btnSoma").onclick)
Instead you can pass in some value you can use to determine the action. In teh example code I am passing in a parameter to indicate the action I want to happen:
Add:'+', Subract:'-', Multiply:'*' and divide:'/'
There are other ways to accomplish this, including having each onclick
call a different function.
But this should help.
Sorry, i'm late. Thanks for your help, now its working!
– César N.
Nov 19 at 18:12
add a comment |
Here is the code working:
function soma(type)
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
var result;
if (type === '+')
result = s1 + s2;
else if (type === '-')
result = s1 - s2;
else if(type === '*')
result = s1 * s2;
else if(type === '/')
result = s1 / s2;
document.getElementById("resultado").innerHTML = result;
<div class="container text-center">
<input name="Valor 1" id="valor1">
<input name="Valor 2" id="valor2"><br>
<button type="submit" onclick="soma('+')" id="btnSoma">Somar</button><br>
<button type="submit" onclick="soma('-')" id="btnSubtrair">Subtrair</button><br>
<button type="submit" onclick="soma('/')" id="btnDividir">Dividir</button><br>
<button type="submit" onclick="soma('*')" id="btnMultiplicar">Multiplicar</button><br>
<p id="resultado">Resultado</p>
</div>
You can't look at the element to see which was clicked.
if(document.getElementById("btnSoma").onclick)
Instead you can pass in some value you can use to determine the action. In teh example code I am passing in a parameter to indicate the action I want to happen:
Add:'+', Subract:'-', Multiply:'*' and divide:'/'
There are other ways to accomplish this, including having each onclick
call a different function.
But this should help.
Here is the code working:
function soma(type)
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
var result;
if (type === '+')
result = s1 + s2;
else if (type === '-')
result = s1 - s2;
else if(type === '*')
result = s1 * s2;
else if(type === '/')
result = s1 / s2;
document.getElementById("resultado").innerHTML = result;
<div class="container text-center">
<input name="Valor 1" id="valor1">
<input name="Valor 2" id="valor2"><br>
<button type="submit" onclick="soma('+')" id="btnSoma">Somar</button><br>
<button type="submit" onclick="soma('-')" id="btnSubtrair">Subtrair</button><br>
<button type="submit" onclick="soma('/')" id="btnDividir">Dividir</button><br>
<button type="submit" onclick="soma('*')" id="btnMultiplicar">Multiplicar</button><br>
<p id="resultado">Resultado</p>
</div>
You can't look at the element to see which was clicked.
if(document.getElementById("btnSoma").onclick)
Instead you can pass in some value you can use to determine the action. In teh example code I am passing in a parameter to indicate the action I want to happen:
Add:'+', Subract:'-', Multiply:'*' and divide:'/'
There are other ways to accomplish this, including having each onclick
call a different function.
But this should help.
function soma(type)
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
var result;
if (type === '+')
result = s1 + s2;
else if (type === '-')
result = s1 - s2;
else if(type === '*')
result = s1 * s2;
else if(type === '/')
result = s1 / s2;
document.getElementById("resultado").innerHTML = result;
<div class="container text-center">
<input name="Valor 1" id="valor1">
<input name="Valor 2" id="valor2"><br>
<button type="submit" onclick="soma('+')" id="btnSoma">Somar</button><br>
<button type="submit" onclick="soma('-')" id="btnSubtrair">Subtrair</button><br>
<button type="submit" onclick="soma('/')" id="btnDividir">Dividir</button><br>
<button type="submit" onclick="soma('*')" id="btnMultiplicar">Multiplicar</button><br>
<p id="resultado">Resultado</p>
</div>
function soma(type)
var s1 = parseInt(document.getElementById("valor1").value,10);
var s2 = parseInt(document.getElementById("valor2").value,10);
document.getElementById("resultado").style.display = "block";
var result;
if (type === '+')
result = s1 + s2;
else if (type === '-')
result = s1 - s2;
else if(type === '*')
result = s1 * s2;
else if(type === '/')
result = s1 / s2;
document.getElementById("resultado").innerHTML = result;
<div class="container text-center">
<input name="Valor 1" id="valor1">
<input name="Valor 2" id="valor2"><br>
<button type="submit" onclick="soma('+')" id="btnSoma">Somar</button><br>
<button type="submit" onclick="soma('-')" id="btnSubtrair">Subtrair</button><br>
<button type="submit" onclick="soma('/')" id="btnDividir">Dividir</button><br>
<button type="submit" onclick="soma('*')" id="btnMultiplicar">Multiplicar</button><br>
<p id="resultado">Resultado</p>
</div>
edited Nov 12 at 21:30
answered Nov 12 at 21:05
Intervalia
3,98211031
3,98211031
Sorry, i'm late. Thanks for your help, now its working!
– César N.
Nov 19 at 18:12
add a comment |
Sorry, i'm late. Thanks for your help, now its working!
– César N.
Nov 19 at 18:12
Sorry, i'm late. Thanks for your help, now its working!
– César N.
Nov 19 at 18:12
Sorry, i'm late. Thanks for your help, now its working!
– César N.
Nov 19 at 18:12
add a comment |
You should set up your javascript where
document.getElementById("btnSoma").click(function()
var add = s1 + s2;
document.getElementById("resultado").innerHTML = add;
);
and repeat this for mult, div, subtraction as desired. You do not need to call soma() as an onclick function with this implementation.
Also, the javascript parseInt
function can take two parameters, the value to parse and the radix
which is what base you are processing numbers in. Typically we count in base 10, but some programs may use different bases.
add a comment |
You should set up your javascript where
document.getElementById("btnSoma").click(function()
var add = s1 + s2;
document.getElementById("resultado").innerHTML = add;
);
and repeat this for mult, div, subtraction as desired. You do not need to call soma() as an onclick function with this implementation.
Also, the javascript parseInt
function can take two parameters, the value to parse and the radix
which is what base you are processing numbers in. Typically we count in base 10, but some programs may use different bases.
add a comment |
You should set up your javascript where
document.getElementById("btnSoma").click(function()
var add = s1 + s2;
document.getElementById("resultado").innerHTML = add;
);
and repeat this for mult, div, subtraction as desired. You do not need to call soma() as an onclick function with this implementation.
Also, the javascript parseInt
function can take two parameters, the value to parse and the radix
which is what base you are processing numbers in. Typically we count in base 10, but some programs may use different bases.
You should set up your javascript where
document.getElementById("btnSoma").click(function()
var add = s1 + s2;
document.getElementById("resultado").innerHTML = add;
);
and repeat this for mult, div, subtraction as desired. You do not need to call soma() as an onclick function with this implementation.
Also, the javascript parseInt
function can take two parameters, the value to parse and the radix
which is what base you are processing numbers in. Typically we count in base 10, but some programs may use different bases.
answered Nov 12 at 20:54
rileyjsumner
1851115
1851115
add a comment |
add a comment |
Well, your if statement is incorrect. You are actually only checking if onClick
was defined on your button that you retrieve.
As it has been defined, you will always end up in the first if-block, so you will never really do something else but sums. It is just an eventhandler to indicate what the program would do when you actually click it, which you forward to the soma()
function.
Now, I don't speak the language you seem to be speaking, so having this question be in English, would be helpful, but I am thinking that soma means sum?
If that is the case, you could make as a starting point 4 different functions, that handle the same input, but perform different operations, something like
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" onclick="sum()">Sum</button><br>
<button type="button" onclick="subtract()">Subtract</button><br>
<button type="button" onclick="multiply()">Multiply</button><br>
<button type="button" onclick="divide()">Divide</button><br>
<span id="result"></span>
This would be the easiest version to transform in. Nowadays, people really don't use the onclick
syntax inside html anymore, so you would now rather attach an event inside your javascript, and let it get handled there, for example
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.getElementById('btnSum').addEventListener('click', sum);
document.getElementById('btnSubtract').addEventListener('click', subtract);
document.getElementById('btnDivide').addEventListener('click', divide);
document.getElementById('btnMultiply').addEventListener('click', multiply);
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" id="btnSum">Sum</button><br>
<button type="button" id="btnSubtract">Subtract</button><br>
<button type="button" id="btnMultiply">Multiply</button><br>
<button type="button" id="btnDivide">Divide</button><br>
<span id="result"></span>
This in total doesn't bring a lot, but you could of course change the html slightly to allow for all operators to be handled, and where it finally gets a bit more interesting, because you can finally use the event argument
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.querySelectorAll('[data-operator]').forEach( btn => btn.addEventListener( 'click', calculate ) );
function calculate( eventSource )
const operator = eventSource.target.getAttribute('data-operator');
if (!operator)
return;
// eval should be used carefully here, but it is just demonstrating what you could get to
output
.innerText = eval( `($parseInt(value1.value)) $operator ($parseInt(value2.value))` );
<input id="value1">
<input id="value2"><br>
<button type="button" data-operator="+">Sum</button><br>
<button type="button" data-operator="-">Subtract</button><br>
<button type="button" data-operator="*">Multiply</button><br>
<button type="button" data-operator="/">Divide</button><br>
<span id="result"></span>
Now, for the parseInt, the second argument would be the base, for example
console.log( parseInt( '11', 2 ) ); // input is in binairy format
console.log( parseInt( '11', 10 ) );// input is in decimal format
console.log( parseInt( '11', 16 ) );// input is in hexadecimal format
Sorry, it was overly long, I just wanted to give a step by step example on how you can change your code going forward :(
– Icepickle
Nov 12 at 21:17
add a comment |
Well, your if statement is incorrect. You are actually only checking if onClick
was defined on your button that you retrieve.
As it has been defined, you will always end up in the first if-block, so you will never really do something else but sums. It is just an eventhandler to indicate what the program would do when you actually click it, which you forward to the soma()
function.
Now, I don't speak the language you seem to be speaking, so having this question be in English, would be helpful, but I am thinking that soma means sum?
If that is the case, you could make as a starting point 4 different functions, that handle the same input, but perform different operations, something like
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" onclick="sum()">Sum</button><br>
<button type="button" onclick="subtract()">Subtract</button><br>
<button type="button" onclick="multiply()">Multiply</button><br>
<button type="button" onclick="divide()">Divide</button><br>
<span id="result"></span>
This would be the easiest version to transform in. Nowadays, people really don't use the onclick
syntax inside html anymore, so you would now rather attach an event inside your javascript, and let it get handled there, for example
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.getElementById('btnSum').addEventListener('click', sum);
document.getElementById('btnSubtract').addEventListener('click', subtract);
document.getElementById('btnDivide').addEventListener('click', divide);
document.getElementById('btnMultiply').addEventListener('click', multiply);
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" id="btnSum">Sum</button><br>
<button type="button" id="btnSubtract">Subtract</button><br>
<button type="button" id="btnMultiply">Multiply</button><br>
<button type="button" id="btnDivide">Divide</button><br>
<span id="result"></span>
This in total doesn't bring a lot, but you could of course change the html slightly to allow for all operators to be handled, and where it finally gets a bit more interesting, because you can finally use the event argument
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.querySelectorAll('[data-operator]').forEach( btn => btn.addEventListener( 'click', calculate ) );
function calculate( eventSource )
const operator = eventSource.target.getAttribute('data-operator');
if (!operator)
return;
// eval should be used carefully here, but it is just demonstrating what you could get to
output
.innerText = eval( `($parseInt(value1.value)) $operator ($parseInt(value2.value))` );
<input id="value1">
<input id="value2"><br>
<button type="button" data-operator="+">Sum</button><br>
<button type="button" data-operator="-">Subtract</button><br>
<button type="button" data-operator="*">Multiply</button><br>
<button type="button" data-operator="/">Divide</button><br>
<span id="result"></span>
Now, for the parseInt, the second argument would be the base, for example
console.log( parseInt( '11', 2 ) ); // input is in binairy format
console.log( parseInt( '11', 10 ) );// input is in decimal format
console.log( parseInt( '11', 16 ) );// input is in hexadecimal format
Sorry, it was overly long, I just wanted to give a step by step example on how you can change your code going forward :(
– Icepickle
Nov 12 at 21:17
add a comment |
Well, your if statement is incorrect. You are actually only checking if onClick
was defined on your button that you retrieve.
As it has been defined, you will always end up in the first if-block, so you will never really do something else but sums. It is just an eventhandler to indicate what the program would do when you actually click it, which you forward to the soma()
function.
Now, I don't speak the language you seem to be speaking, so having this question be in English, would be helpful, but I am thinking that soma means sum?
If that is the case, you could make as a starting point 4 different functions, that handle the same input, but perform different operations, something like
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" onclick="sum()">Sum</button><br>
<button type="button" onclick="subtract()">Subtract</button><br>
<button type="button" onclick="multiply()">Multiply</button><br>
<button type="button" onclick="divide()">Divide</button><br>
<span id="result"></span>
This would be the easiest version to transform in. Nowadays, people really don't use the onclick
syntax inside html anymore, so you would now rather attach an event inside your javascript, and let it get handled there, for example
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.getElementById('btnSum').addEventListener('click', sum);
document.getElementById('btnSubtract').addEventListener('click', subtract);
document.getElementById('btnDivide').addEventListener('click', divide);
document.getElementById('btnMultiply').addEventListener('click', multiply);
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" id="btnSum">Sum</button><br>
<button type="button" id="btnSubtract">Subtract</button><br>
<button type="button" id="btnMultiply">Multiply</button><br>
<button type="button" id="btnDivide">Divide</button><br>
<span id="result"></span>
This in total doesn't bring a lot, but you could of course change the html slightly to allow for all operators to be handled, and where it finally gets a bit more interesting, because you can finally use the event argument
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.querySelectorAll('[data-operator]').forEach( btn => btn.addEventListener( 'click', calculate ) );
function calculate( eventSource )
const operator = eventSource.target.getAttribute('data-operator');
if (!operator)
return;
// eval should be used carefully here, but it is just demonstrating what you could get to
output
.innerText = eval( `($parseInt(value1.value)) $operator ($parseInt(value2.value))` );
<input id="value1">
<input id="value2"><br>
<button type="button" data-operator="+">Sum</button><br>
<button type="button" data-operator="-">Subtract</button><br>
<button type="button" data-operator="*">Multiply</button><br>
<button type="button" data-operator="/">Divide</button><br>
<span id="result"></span>
Now, for the parseInt, the second argument would be the base, for example
console.log( parseInt( '11', 2 ) ); // input is in binairy format
console.log( parseInt( '11', 10 ) );// input is in decimal format
console.log( parseInt( '11', 16 ) );// input is in hexadecimal format
Well, your if statement is incorrect. You are actually only checking if onClick
was defined on your button that you retrieve.
As it has been defined, you will always end up in the first if-block, so you will never really do something else but sums. It is just an eventhandler to indicate what the program would do when you actually click it, which you forward to the soma()
function.
Now, I don't speak the language you seem to be speaking, so having this question be in English, would be helpful, but I am thinking that soma means sum?
If that is the case, you could make as a starting point 4 different functions, that handle the same input, but perform different operations, something like
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" onclick="sum()">Sum</button><br>
<button type="button" onclick="subtract()">Subtract</button><br>
<button type="button" onclick="multiply()">Multiply</button><br>
<button type="button" onclick="divide()">Divide</button><br>
<span id="result"></span>
This would be the easiest version to transform in. Nowadays, people really don't use the onclick
syntax inside html anymore, so you would now rather attach an event inside your javascript, and let it get handled there, for example
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.getElementById('btnSum').addEventListener('click', sum);
document.getElementById('btnSubtract').addEventListener('click', subtract);
document.getElementById('btnDivide').addEventListener('click', divide);
document.getElementById('btnMultiply').addEventListener('click', multiply);
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" id="btnSum">Sum</button><br>
<button type="button" id="btnSubtract">Subtract</button><br>
<button type="button" id="btnMultiply">Multiply</button><br>
<button type="button" id="btnDivide">Divide</button><br>
<span id="result"></span>
This in total doesn't bring a lot, but you could of course change the html slightly to allow for all operators to be handled, and where it finally gets a bit more interesting, because you can finally use the event argument
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.querySelectorAll('[data-operator]').forEach( btn => btn.addEventListener( 'click', calculate ) );
function calculate( eventSource )
const operator = eventSource.target.getAttribute('data-operator');
if (!operator)
return;
// eval should be used carefully here, but it is just demonstrating what you could get to
output
.innerText = eval( `($parseInt(value1.value)) $operator ($parseInt(value2.value))` );
<input id="value1">
<input id="value2"><br>
<button type="button" data-operator="+">Sum</button><br>
<button type="button" data-operator="-">Subtract</button><br>
<button type="button" data-operator="*">Multiply</button><br>
<button type="button" data-operator="/">Divide</button><br>
<span id="result"></span>
Now, for the parseInt, the second argument would be the base, for example
console.log( parseInt( '11', 2 ) ); // input is in binairy format
console.log( parseInt( '11', 10 ) );// input is in decimal format
console.log( parseInt( '11', 16 ) );// input is in hexadecimal format
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" onclick="sum()">Sum</button><br>
<button type="button" onclick="subtract()">Subtract</button><br>
<button type="button" onclick="multiply()">Multiply</button><br>
<button type="button" onclick="divide()">Divide</button><br>
<span id="result"></span>
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" onclick="sum()">Sum</button><br>
<button type="button" onclick="subtract()">Subtract</button><br>
<button type="button" onclick="multiply()">Multiply</button><br>
<button type="button" onclick="divide()">Divide</button><br>
<span id="result"></span>
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.getElementById('btnSum').addEventListener('click', sum);
document.getElementById('btnSubtract').addEventListener('click', subtract);
document.getElementById('btnDivide').addEventListener('click', divide);
document.getElementById('btnMultiply').addEventListener('click', multiply);
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" id="btnSum">Sum</button><br>
<button type="button" id="btnSubtract">Subtract</button><br>
<button type="button" id="btnMultiply">Multiply</button><br>
<button type="button" id="btnDivide">Divide</button><br>
<span id="result"></span>
// get the element once, the values you can just retrieve when needed
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.getElementById('btnSum').addEventListener('click', sum);
document.getElementById('btnSubtract').addEventListener('click', subtract);
document.getElementById('btnDivide').addEventListener('click', divide);
document.getElementById('btnMultiply').addEventListener('click', multiply);
function getValuesFromInput()
return
a: parseInt( value1.value ),
b: parseInt( value2.value )
;
function setOutput( result )
output.innerText = result;
function sum()
const a, b = getValuesFromInput();
setOutput( a + b );
function subtract()
const a, b = getValuesFromInput();
setOutput( a - b );
function multiply()
const a, b = getValuesFromInput();
setOutput( a * b );
function divide()
const a, b = getValuesFromInput();
setOutput( a / b );
<input id="value1">
<input id="value2"><br>
<button type="button" id="btnSum">Sum</button><br>
<button type="button" id="btnSubtract">Subtract</button><br>
<button type="button" id="btnMultiply">Multiply</button><br>
<button type="button" id="btnDivide">Divide</button><br>
<span id="result"></span>
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.querySelectorAll('[data-operator]').forEach( btn => btn.addEventListener( 'click', calculate ) );
function calculate( eventSource )
const operator = eventSource.target.getAttribute('data-operator');
if (!operator)
return;
// eval should be used carefully here, but it is just demonstrating what you could get to
output
.innerText = eval( `($parseInt(value1.value)) $operator ($parseInt(value2.value))` );
<input id="value1">
<input id="value2"><br>
<button type="button" data-operator="+">Sum</button><br>
<button type="button" data-operator="-">Subtract</button><br>
<button type="button" data-operator="*">Multiply</button><br>
<button type="button" data-operator="/">Divide</button><br>
<span id="result"></span>
const value1 = document.getElementById('value1');
const value2 = document.getElementById('value2');
const output = document.getElementById('result');
document.querySelectorAll('[data-operator]').forEach( btn => btn.addEventListener( 'click', calculate ) );
function calculate( eventSource )
const operator = eventSource.target.getAttribute('data-operator');
if (!operator)
return;
// eval should be used carefully here, but it is just demonstrating what you could get to
output
.innerText = eval( `($parseInt(value1.value)) $operator ($parseInt(value2.value))` );
<input id="value1">
<input id="value2"><br>
<button type="button" data-operator="+">Sum</button><br>
<button type="button" data-operator="-">Subtract</button><br>
<button type="button" data-operator="*">Multiply</button><br>
<button type="button" data-operator="/">Divide</button><br>
<span id="result"></span>
console.log( parseInt( '11', 2 ) ); // input is in binairy format
console.log( parseInt( '11', 10 ) );// input is in decimal format
console.log( parseInt( '11', 16 ) );// input is in hexadecimal format
console.log( parseInt( '11', 2 ) ); // input is in binairy format
console.log( parseInt( '11', 10 ) );// input is in decimal format
console.log( parseInt( '11', 16 ) );// input is in hexadecimal format
answered Nov 12 at 21:16
Icepickle
8,60032036
8,60032036
Sorry, it was overly long, I just wanted to give a step by step example on how you can change your code going forward :(
– Icepickle
Nov 12 at 21:17
add a comment |
Sorry, it was overly long, I just wanted to give a step by step example on how you can change your code going forward :(
– Icepickle
Nov 12 at 21:17
Sorry, it was overly long, I just wanted to give a step by step example on how you can change your code going forward :(
– Icepickle
Nov 12 at 21:17
Sorry, it was overly long, I just wanted to give a step by step example on how you can change your code going forward :(
– Icepickle
Nov 12 at 21:17
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53269842%2fcalculator-giving-wrong-results-in-js%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
3
document.getElementById("btnMultiplicar").onclick
is an event handler. It's a function that fires when the button with that ID is clicked. You can't use it in the manner that you have. In regards toparseInt
: thevalue
property is astring
. If you add two strings"5" + "5"
, it's"55"
. If you add two numbers5 + 5
, it's10
.parseInt
changes"5"
to5
, for example.– Tyler Roper
Nov 12 at 20:48