Im making a Calculator project, I have made a function which gets the user input inside the input tag and A eval() function that will calculate it and prints it on output tab.
But I want to replace eval(), and want the same funcationality under the input tab.
-> here is my js code-
const userInput= document.getElementById('input');
const userOutput= document.getElementById('output');
const clearbtn= document.getElementById('clear');
const calBtn=document.getElementById('calcBtn')
//selecting all the input btns at all
const btns= document.querySelectorAll('input[type="button"]');
function calc(){
//looping through each btns
btns.forEach(button =>{
button.addEventListener('click',()=>{
let btnDataType= button.dataset.type;
if(btnDataType==='number'|| btnDataType==='operator'){
//appending the value;
userInput.value+= button.value;
}
})
})
//it will clear the input display
clearbtn.addEventListener('click',()=>{
userInput.value='';
userOutput.value='';
})
calBtn.addEventListener('click',()=>{
try{
console.log("Input value:", userInput.value);
userOutput.value= eval(userInput.value);
}
catch(e){
userOutput.value='Invalid selection';
}
});
}
calc();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link href="style.css" rel="stylesheet">
</head>
<body >
<!-- header section -->
<header>
<nav>
<a href="">Logo</a>
<button>contribute here</button>
</nav>
</header>
<!-- main -->
<main>
<section>
<!-- calculator wrapper div -->
<div>
<!-- input and output screens -->
<div>
<input type="text" placeholder="Type to Calculate" id="input">
<input type="text" placeholder="Output" readonly id="output">
<button id="clear">Clear</button>
</div>
<!-- wrapper that contains number btns , operators -->
<div>
<!-- numbers -->
<div>
<input type="button" value="0" id="0" data-type="number">
<input type="button" value="1" id="1" data-type="number">
<input type="button" value="2" id="2" data-type="number">
<input type="button" value="3" id="3" data-type="number">
<input type="button" value="4" id="4" data-type="number">
<input type="button" value="5" id="5" data-type="number">
<input type="button" value="6" id="6" data-type="number">
<input type="button" value="7" id="7" data-type="number">
<input type="button" value="8" id="8" data-type="number">
<input type="button" value="9" id="9" data-type="number">
</div>
<!-- operators btns -->
<div>
<input type="button" value="+" id="+" data-type="operator">
<input type="button" value="-" id="-" data-type="operator">
<input type="button" value="*" id="*" data-type="operator">
<input type="button" value="/" id="/" data-type="operator">
<input type="button" value="%" id="%" data-type="operator">
<button id="calcBtn">Calculate</button>
</div>
</div>
</div>
</section>
</main>
</body>
<script src="app.js"></script>
</html>
strong text
i kinnda stuck in logic building , any suggestion will help me.