I've an assignment for school in which I have to do a basic calculator using JS, but I can't get the result returned into the textbox. Here's my code:
<form>
<input type="textbox" id="val1"> Primo valore
<br><br>
<input type="textbox" id="val2"> Secondo valore
<br><br>
<script>
function getFloatValue(x) {
var xf = parseFloat(x.value)
return xf
}
</script>
<script>
var a = document.getElementById("val1")
var b = document.getElementById("val2")
var af = getFloatValue(a)
var bf = getFloatValue(b)
function calculate(a,b,op) {
var r
switch (op.value) {
case '+': return a+b
case '-': return a-b
case '/': return a/b
case '*': return a*b
}
}
</script>
<input type="button" value="+" onclick="document.getElementById('result').value = calculate(af, bf, '+')">
<input type="button" value="-" onclick="document.getElementById('result').value = calculate(af, bf, '-')">
<input type="button" value="/" onclick="document.getElementById('result').value = calculate(af, bf, '/')">
<input type="button" value="*" onclick="document.getElementById('result').value = calculate(af, bf, '*')">
<br><br>
<input type="textbox" id="result" value=''> Risultato
<br><br>
<input type="reset" name="reset" value="Resetta tutto">
</form>
I've made lots of tries, but noone of these worked :\
Thank you in advance :D
Instead of passing variables, Pass element ID attributes so that we can access elements using id
op.value does not make sense as you are passing hard-coded string for signs
function getFloatValue(x) {
return parseFloat(x.value);
}
function calculate(a, b, op) {
var a = document.getElementById(a);
var b = document.getElementById(b);
a = getFloatValue(a);
b = getFloatValue(b);
var r
switch (op) {
case '+':
return a + b
case '-':
return a - b
case '/':
return a / b
case '*':
return a * b
}
}
<form>
<input type="textbox" id="val1">Primo valore
<br>
<br>
<input type="textbox" id="val2">Secondo valore
<br>
<br>
<input type="button" value="+" onclick="document.getElementById('result').value = calculate('val1', 'val2', '+')">
<input type="button" value="-" onclick="document.getElementById('result').value = calculate('val1', 'val2', '-')">
<input type="button" value="/" onclick="document.getElementById('result').value = calculate('val1', 'val2', '/')">
<input type="button" value="*" onclick="document.getElementById('result').value = calculate('val1', 'val2', '*')">
<br>
<br>
<input type="textbox" id="result" value=''>Risultato
<br>
<br>
<input type="reset" name="reset" value="Resetta tutto">
</form>
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Related
I've got almost no experience with Javascript and I need make a "calculator" type website.
This is the part of the code that is suppose to calculate, but it only adds values together instead of calculating them.
I was told parseInt will fix this, but due to my inexperience I can't find how to do so through Google.
Any help is appreciated and explenations are welcome. Thanks!
function izracunaj() {
const st1 = document.getElementById("prvoStevilo").value;
//določim konstantno ki bo pridobila informacije iz polja kjer smo določili id
const st2 = document.getElementById("drugoStevilo").value;
const operacija = document.getElementById("operacija").value;
let rezultat;
switch (operacija) {
//v oklepaje vpišemo operacija, saj to preverjamo
case '+':
rezultat = st1+st2;
break;
//podatki se skranijo v rezultat
case '-':
rezultat = st1-st2;
break;
case '*':
rezultat = st1*st2;
break;
case '/':
rezultat = st1/st2;
break;
}
document.getElementById("rezultat").value = rezultat;
}
<!DOCTYPE html>
<html>
<head>
<title>Kalkulator</title>
<script src="javascript.js"></script>
</head>
<body>
<h1>Kalkulator</h2>
<form>
Prvo število: <br>
<input type="text" id="prvoStevilo"> <br>
Drugo število: <br>
<input type="text" id="drugoStevilo"> <br>
Operacija: <br>
<input type="text" id="operacija"> <br>
Rezultat: <br>
<input type="text" id="rezultat" disabled="true"> <br>
<br><br>
<input type="button" value="Izračunaj" onclick="izracunaj()">
</form>
</body>
</html>
When you use .value then it will give you the value of type string. All you have to do is either use parseInt or use + to convert it into number type
parseInt(document.getElementById("prvoStevilo").value, 10);
or
+document.getElementById("prvoStevilo").value;
or
Number(document.getElementById("prvoStevilo").value);
function izracunaj() {
const st1 = parseInt(document.getElementById("prvoStevilo").value); // change
//določim konstantno ki bo pridobila informacije iz polja kjer smo določili id
const st2 = +document.getElementById("drugoStevilo").value; // change
const operacija = document.getElementById("operacija").value;
let rezultat;
switch (operacija) {
//v oklepaje vpišemo operacija, saj to preverjamo
case '+':
rezultat = st1 + st2;
break;
//podatki se skranijo v rezultat
case '-':
rezultat = st1 - st2;
break;
case '*':
rezultat = st1 * st2;
break;
case '/':
rezultat = st1 / st2;
break;
}
document.getElementById("rezultat").value = rezultat;
}
<h1>Kalkulator</h2>
<form>
Prvo število: <br>
<input type="text" id="prvoStevilo"> <br> Drugo število: <br>
<input type="text" id="drugoStevilo"> <br> Operacija: <br>
<input type="text" id="operacija"> <br> Rezultat: <br>
<input type="text" id="rezultat" disabled="true"> <br>
<br><br>
<input type="button" value="Izračunaj" onclick="izracunaj()">
</form>
You could also let javascript evaluate the equation for you using Function. I multiply the first two arguments by 1 to force them to either NaN or numeric values, and limit the operator to the four values in the regex in order to sanitize the inputs, then combine the arguments into a string with a template literal.
function izracunaj() {
const st1 = document.getElementById("prvoStevilo").value*1;
const st2 = document.getElementById("drugoStevilo").value*1;
const operacija = document.getElementById("operacija").value;
if(!/[+-/*]/.test(operacija)) { return; }
let formula = `return ${st1}${operacija}${st2}`;
let rezultat = new Function(formula);
document.getElementById("rezultat").value = rezultat();
}
<!DOCTYPE html>
<html>
<head>
<title>Kalkulator</title>
<script src="javascript.js"></script>
</head>
<body>
<h1>Kalkulator</h2>
<form>
Prvo število: <br>
<input type="text" id="prvoStevilo"> <br>
Drugo število: <br>
<input type="text" id="drugoStevilo"> <br>
Operacija: <br>
<input type="text" id="operacija"> <br>
Rezultat: <br>
<input type="text" id="rezultat" disabled="true"> <br>
<br><br>
<input type="button" value="Izračunaj" onclick="izracunaj()">
</form>
</body>
</html>
I am trying to read the value from an input text, and make all the math operations at once
I have gotten to calculate one operation such as 25+67 but I cannot make to read and split more complex operations such as 50+5*5, I do not know how to get the different values and make operations one by one, I have tried creating a loop using split everytime it finds something different than a number but it is not working
Where screen is the id of the input where you can write down all the numbers and operations you like
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="js/data.js"></script>
<title>Calculator</title>
</head>
<body>
<div class="mycalc">
<form name="calculator" id="calculator" class="cuerpo">
<h2 class="casio">CASIO</h2>
<input type="text" name="screen" id="screen" readonly>
<div>
<input type="button" id="one" value="1" onclick="takeValue(1)">
<input type="button" id="two" value="2" onclick="takeValue(2)">
<input type="button" id="three" value="3" onclick="takeValue(3)">
<input type="button" id="add" value="+" onclick="takeValue('+')">
</div>
<div>
<input type="button" id="four" value="4" onclick="takeValue(4)">
<input type="button" id="five" value="5" onclick="takeValue(5)">
<input type="button" id="six" value="6" onclick="takeValue(6)">
<input type="button" id="sus" value="-" onclick="takeValue('-')">
</div>
<div>
<input type="button" id="seven" value="7" onclick="takeValue(7)">
<input type="button" id="eight" value="8" onclick="takeValue(8)">
<input type="button" id="nine" value="9" onclick="takeValue(9)">
<input type="button" id="mul" value="*" onclick="takeValue('*')">
</div>
<div>
<input type="button" id="zero" value="0" onclick="takeValue(0)">
<button type="button" id="clear" value="" onclick="clearInput()">AC</button>
<input type="button" id="zero" value="="onclick="prueba()">
<input type="button" id="div" value="/" onclick="takeValue('/')">
</div>
</form>
</div>
</body>
</html>
function checkOperation(num1,num2, oper){
let res;
switch(oper){
case "+":
res = parseInt(num1) + parseInt(num2);
break;
case "-":
res = parseInt(num) + parseInt(num2);
break;
case "*":
res = parseInt(num1) + parseInt(num2);
break;
case "/":
res = parseInt(num1) + parseInt(num2);
break;
}
return res;
}
function prueba(){
let actual = document.getElementById('screen').value;
let arr = [];
let res = 0;
let res1 = 0;
let temp;
for(let i = 0; i < actual.length; i++){
if(isNaN(actual[i])){
let oper1 = actual[i];
arr = actual.split(oper1);
temp = arr[1];
for(let j = 0; j < temp.length; j++){
if(isNaN(temp[j])){
let oper2 = temp[j];
let num1 = temp[0];
let num2 = temp[1];
res = checkOperation(num1, num2, oper2)
}
}
res1 = checkOperation(parseInt(temp), res, oper1)
}
}
document.getElementById('screen').value = res1;
}
You can try using JavaScript's eval() function.
const a = eval('25+67');
const b = eval('50+5*5');
console.log(a);
console.log(b);
However, do note that there are various security risks involved when using that function, hence you should be careful when it comes to using it on production code.
I am having trouble, as you can see in code, for the result3 as id i have op1, what I would like to have there so that it works is that id changes depending on the button pressed, how can I do that? because now every button is like a +.
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
</head>
<script>
function getResult()
{
var result1 = document.getElementById("number1").value;
var result3 = document.getElementById ("op1").value;
var result2 = document.getElementById("number2").value;
calculate (result1,result3,result2);
}
function calculate(num1,operator,num2)
{
if (operator== '+')
{
var res1 = parseFloat(num1)+parseFloat(num2);
alert(res1);
}
else if (operator== '-')
{
var res2 = parseFloat(num1)-parseFloat(num2);
alert(res2);
}
else if (operator== '*')
{
var res3 = parseFloat(num1)*parseFloat(num2);
alert(res3);
}
else if (operator== '/')
{
var res4 = parseFloat(num1)/parseFloat(num2);
alert(res4);
}
else
{
alert("Nothing from above!");
}
}
</script>
<body>
<form action="get" method="#">
<input type="text" name="text1" value="" id="number1" /> <br/>
<input type="text" name="text2" value="" id="number2" /> <br/>
<input type="button" name="o1" value="+" id="op1" onclick="getResult();"/>
<input type="button" name="o2" value="-" id="op2" onclick="getResult();"/>
<input type="button" name="o3" value="*" id="op3" onclick="getResult();"/>
<input type="button" name="o4" value="/" id="op4" onclick="getResult();"/>
<input type="button" name="calc" value="Calculate" onclick="getResult();"/>
</form>
</body>
</html>
You are always calling the value of input with id="op1", which is + in your case. Why not pass the value?
getResult(id) {
var result1 = document.getElementById("number1").value;
var result3 = document.getElementById (id).value;
var result2 = document.getElementById("number2").value;
calculate (result1,result3,result2);}
The id is passed when calling the function:
<input type="button" name="o1" value="+" id="op1" onclick="getResult(id);"/>
<input type="button" name="o2" value="-" id="op2" onclick="getResult(id);"/>
<input type="button" name="o3" value="*" id="op3" onclick="getResult(id);"/>
<input type="button" name="o4" value="/" id="op4" onclick="getResult(id);"/>
Calculate button won't work this way, but this is a quick fix with your setup. Good luck.
I'm trying to make JavaScript calculator. I want to create simple addition function in JavaScript but didn't know how to build that logic, need someone help, and in my code one input text field is present.
Code contain input buttons which is numbers now I need help. So how do I do addition function in JavaScript?
function plus()
{
var textInputval=0;
var textInputval1=2;
var temp=0;
textInputval = parseInt(document.getElementById('new').value);
textInputval1 = parseInt(document.getElementById('new').value);
temp = textInputval + textInputval1;
console.log(textInputval);
console.log(textInputval1);
}
<div id = "cal-container">
<form name="calculator">
<input type="text" name="answer" value="" id="new">
<br>
<input type="button" value=" 1 " onclick="one()" />
<input type="button" value=" 2 " onclick="two()" />
<input type="button" value=" 3 " onclick="three()" />
<input type="button" value=" + " onclick="plus()" />
</form>
</div>
function action(method) {
var a = parseInt(document.getElementById("num1").value);
var b = parseInt(document.getElementById("num2").value);
var result = null;
switch (method) {
case 'add':
result = a + b;
break;
case 'subtract':
result = a - b;
break;
case 'multiply':
result = a * b;
break;
case 'divide':
if (b != 0) {
result = a / b;
} else {
alert('Can\'t divide by 0');
return;
}
break;
}
if (result !== null) {
document.getElementById("result").value = result;
} else {
document.getElementById("num1").value = "";
document.getElementById("num2").value = "";
document.getElementById("result").value = "";
}
}
<span style="margin-right:1px">Number 1 </span>
<input id="num1" type="number"></br>
<span style="margin-right:5px">Number 2</span><input id="num2" type="number"></br>
<span style="margin-right:29px">Result</span><input id="result" type="number"> </br>
<button id="add" onclick="action('add')">+</button>
<button id="subtract" onclick="action('subtract')">-</button>
<button id="multiply" onclick="action('multiply')">*</button>
<button id="divide" onclick="action('divide')">/</button>
<button id="clear" onclick="action('clear')">clear</button>
So i have a problem with creating a calculator in HTML and Java script for my homework and i don't know what is wrong with it. For some reason after i added sqrt function buttons are no longer working and i can't realy find an answer, pls help...
JavaScript:
var liczba1,liczba2,znak,flaga_przecinek
function liczba(cyfra)
{
var a = document.getElementById("licz").innerHTML
if(a == "0")document.getElementById("licz").innerHTML = cyfra
else document.getElementById("licz").innerHTML += cyfra
}
function dzialanie(operacja)
{
liczba1 = document.getElementById("licz").innerHTML
znak = operacja
document.getElementById("licz").innerHTML = 0
flaga_przecinek = false
}
function wynik()
{
liczba2 = document.getElementById("licz").innerHTML
var wynik1
switch wynik()
{
case '+': wynik1 = parseFloat(liczba1) + parseFloat(liczba2)
break
case '-': wynik1 = parseFloat(liczba1) - parseFloat(liczba2)
break
case '*': wynik1 = parseFloat(liczba1) * parseFloat(liczba2)
break
case '/': if (liczba2 == '0')
wynik1 = 'Nie można dzielić przez 0'
else
case '/': wynik1 = parseFloat(liczba1) / parseFloat(liczba2)
break
case '^': wynik1 = 1
for (vard i = 1;i<=liczba2;i++)wynik1 = wynik1*liczba1
break
}
if(!isNaN(wynik1)||wynik1 == 'Nie można dzielić przez 0')
document.getElementById("licz").innerHTML = wynik1
else
document.getElementById("licz").innerHTML = 'Nie podałeś liczby'
}
function kasuj()
{
liczba1 = liczba2 = 0
znak = ''
document.getElementById("licz").innerHTML = 0
flaga_przecinek = false
}
function przecinek()
{
if (flaga_przecinek == false)
{
document.getElementById("licz").innerHTML += '.'
flaga_przecinek = true
}
}
function bekspejs()
{
var x = document.getElementById("licz").innerHTML
if(x.charAt(xlenght-1)=='.'flaga_przecinek = false
x = x.slice(0,x.lenght-1)
document.getElementById("licz").innerHTML = x
}
function operacja1(operacja)
{
var x = document.getElementById("licz").innerHTML
switch(operacja)
{
case 'sqrt':x = Math.sqrt(x)
break
case '+/-':x = -1*x
break
}
document.getElementById("licz").innerHTML = x
}
HTML:
<body onload=kasuj()>
<form name=kalkulator>
<p id=licz></p>
<br><br>
<input type="button" value=C onclick=kasuj()>
<input type="button" value="<-" onclick=bekspejs()>
<br><br>
<input type="button" value=1 onclick=liczba(1)>
<input type="button" value=2 onclick=liczba(2)>
<input type="button" value=3 onclick=liczba(3)>
<br>
<input type="button" value=4 onclick=liczba(4)>
<input type="button" value=5 onclick=liczba(5)>
<input type="button" value=6 onclick=liczba(6)>
<br>
<input type="button" value=7 onclick=liczba(7)>
<input type="button" value=8 onclick=liczba(8)>
<input type="button" value=9 onclick=liczba(9)>
<br>
<input type="button" value=0 onclick=liczba(0)>
<input type="button" value=, onclick=przecinek()>
<br><br>
<input type="button" value=+ onclick=dzialanie('+')>
<input type="button" value=- onclick=dzialanie('-')>
<input type="button" value=* onclick=dzialanie('*')>
<input type="button" value=/ onclick=dzialanie('/')>
<input type="button" value=^ onclick=dzialanie('^')>
<br>
<input type="button" value=sqrt onclick=operacja1('sqrt')>
<input type="button" value=+/- onclick=operacja1('+/-')>
<br>
<input type="button" value== onclick=wynik()>
</form>
</body>
try Wrapping all the onclick events and value attributes in double qoutes onclick="przecinek()" value="+"
<input type="button" value="8" onclick="przecinek(8)">
<input type="button" value="9" onclick="przecinek(9)">