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>
Related
I was just trying to write a simple javascript program that will demonstrate to take user input from text field, and clicking the button will display the summation result of those number in a paragraph. But unfortunately the below code is not working. Clicking the button shows NAN in the Paragraph.
<input type="text" name="" id="num1"><br><br>
<input type="text" name="" id="num2"><br> <br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
<script>
let num1=parseInt(document.getElementById("num1"));
let num2=parseInt(document.getElementById("num2"));
let add=document.getElementById("add");
add.addEventListener("click",function(){
document.getElementById("para").innerHTML=num1+num2;
});
</script>
You are getting the elementById, but not getting that IDs value.
Add .value on the end of your getElementById
function addTogether()
{
var val1 = document.getElementById('val1').value;
var val2 = document.getElementById('val2').value;
var sum = parseInt(val1) + parseInt(val2);
console.log(sum);
}
<input type="text" id="val1" />
<input type="text" id="val2" />
<input type="button" value="Add Them Together" onclick="addTogether();" />
You can simply do it like this
<input type="text" id="num1"><br><br>
<input type="text" id="num2"><br><br>
<button id="add">Answer</button><br>
<p id="para"></p>
<script>
let add=document.getElementById("add");
add.addEventListener("click",function(){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var res = parseInt(num1) + parseInt(num2);
document.getElementById("para").innerHTML = res ;
});
</script>
here is the demo of working code
let add=document.getElementById("add");
add.addEventListener("click",function(){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var res = parseInt(num1) + parseInt(num2);
document.getElementById("para").innerHTML = res ;
});
<input type="text" id="num1"><br><br>
<input type="text" id="num2"><br><br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
you need to get the value of num1 and num2 and you need to get the value after you click -- so inside your function
<input type="text" name="" id="num1"><br><br>
<input type="text" name="" id="num2"><br> <br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
<script>
let add=document.getElementById("add");
add.addEventListener("click",function(){
let num1=parseInt(document.getElementById("num1").value);
let num2=parseInt(document.getElementById("num2").value);
document.getElementById("para").innerHTML=num1+num2;
});
</script>
I 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'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);
}
I created this calculator with two pages. The first page contains a registration form, the second page contains the calculator
html for first page :
<!DOCTYPE html>
<html>
<head>
<title>js assigment 1 _ omar azzazy</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div class="container">
<h1>Registration form</h1>
<form action="calc.html">
First Name: <input type="text"/><br><br>
Last Name: <input type="text"/><br>
Gender:
<input id="m" type="radio" name="gender" value="male"/> Male <br>
<input id="f" type="radio" name="gender" value="female"/>Female <br>
<input type="submit" onclick="go()" value="Go to calculator">
</form>
</div>
<script src="js/plugin.js"></script>
</body>
html for second page :
<!DOCTYPE html>
<html>
<head>
<title>js assigment 1 _ omar azzazy</title>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<div class="container">
<h1>calculator</h1>
<input id="operator1" type="number" value=""/>
<select id="operatorx">
<option value="0">+</option>
<option value="1">-</option>
<option value="2">x</option>
<option value="3">/</option>
</select>
<input id="operator2" type="number" value=""/>
<button onclick="calc()">=</button>
<input id="result" type="text" value=""/>
</div>
<script src="js/plugin.js"></script>
</body>
</html>
javascript code:
function plus(a, b) {
return (a + b);
}
function minus(a, b) {
return (a - b);
}
function multiply(a, b) {
return (a * b);
}
function divide(a, b) {
return (a / b);
}
function calc() {
var x = parseFloat( document.getElementById("operator1").value );
var y = document.getElementById("operatorx").value;
var z = parseFloat( document.getElementById("operator2").value );
switch (y) {
case '0':
w = plus(x, z);
break;
case '1':
w = minus(x, z);
break;
case '2':
w = multiply(x, z);
break;
case '3':
w = divide(x, z);
break;
default:
w = "Don't really know..";
}
document.getElementById("result").value = w;
}
I need if the user selected "Male" in radio button the page and calculator buttons will be in colors suitable for Men mood.
If the user selected "Female" the page and calculator buttons will be in colors suitable for Women mood.
You need to first check which was selected using document.getElementById("id").checked = true;
then use the "style" element of javascript to add your styles, or create add and remove as suggested here:
Change an element's class with JavaScript
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)">