Reputation: 379
I am making a calculator in javascript. And when ever I clicked the buttons like add,subtract it is calling the function of delete button. My logic is to check the id first and then call the function accordingly. And even if all buttons have different id, del id condition code is running.
HTML
<div class="row" id="first-row">
<div class="btn red-btn" id="ac">
<p class="text shift-left-sm">AC</p>
</div>
<div class="btn red-btn" id="del">
<p class="text shift-left-sm">DE</p>
</div>
<div class="btn" id="/">
<p class="text number">÷</p>
</div>
<div class="btn rightmost" id="*">
<p class="text number">x</p>
</div>
</div>
Javascript
const text = document.querySelector("#header-text");
const buttons = document.querySelectorAll(".btn");
const numbers =['1','2','3','4','5','6','7','8','9','0'];
const mathFunc =['ac','del','/','*','-','+','.','equal'];
let displayText ='0';
const firstLetterZeroReg =/0\b/;
for(var i=0;i<buttons.length;i++){
buttons[i].addEventListener('click',function(e){
let attr = this.getAttribute('id');
// when you are pressing a number button
if(numbers.includes(attr)){
if(attr=="0" && lastLetterOfText() =="0"){
//if initially it is zero and you are trying to add more zero. it will stop that
return;
}
if(displayText.match(firstLetterZeroReg)){// regular expression is used which is not necessary at all. Just lazy to remove it
//If initially it is zero and you press the first button zero is erased
displayText =attr;
UpdateDisplay();
return;
}
displayText+=attr;
UpdateDisplay();
}else{
//when you are pressing a function button
// console.log(attr);
// console.log(displayText);
if(attr=="ac"){
EraseEverything();
}else if(attr="del"){
//removes the last letter typed
//PROBLEM IS IN THIS LINE
// This line is being called for other attr too
Del();
}else if(attr!=lastLetterOfText()){
//merely checks if we are not pressing the same button twice
console.log("this also being called");
if(attr==="."){
displayText+=attr;
console.log(displayText);
UpdateDisplay();
}
}else{
console.log("SOme other button is pressed");
}
}
})
}
Upvotes: 1
Views: 383
Reputation: 627
You're using an assignment operator instead of comparison
else if (attr="del")
It should be
else if (attr=="del")
Upvotes: 2