Home > database >  how can I add a new value and delete the old one from a .innerText
how can I add a new value and delete the old one from a .innerText

Time:11-15

I'm starting to study programming and I am trying to make a calculator with html css js with my learning so far. But I got stuck in one part: my calculator shows the value typed in currentvalue.innerText and when it receives an operation, the value appears on top of it, in previousvalue.innerText, I wanted the currentvalue to be reset only when the person inserts a new number, then I could extract the new value in a variable called num2 and use it to do the math

this is the part of the function that I am talking about:

function insert(value){        
    
    if (value === '/'|| value ==='*'|| value === '-'|| value === ' '){
        
        previousOperation.innerText = currentOperation.textContent   ` ${value}`;
        num1 = previousOperation.innerText.slice(0, -2);
        
        op = value;

        return
    }
    
    if(value === '.') {    
        currentOperation.innerText  = '.'; // O '0' inicial permanece e é adicionado um ponto
    } else if (currentOperation.innerText === '0'){ // Exclui o 0 inicial e adiciona o value digitado direto
        currentOperation.innerText = value;
    } else {
        currentOperation.innerText  = value;
    } 
}

I tried resetting the currentvalue.innerText, but only when the previoustvalue.innerText already had a value, but doing that it only shows one number at a time in my currentvalue.innerText, it doesn't save the value and show all the others typed

CodePudding user response:

You must convert 'currentOperation.innerText' and 'value' to numbers before applying the formula.

if(value === '.') {    
    currentOperation.innerText  = '.'; // O '0' inicial permanece e é adicionado um ponto
} else if (currentOperation.innerText === '0'){ // Exclui o 0 inicial e adiciona o value digitado direto
    currentOperation.innerText = value;
} else {
    const previousNumber = parseInt(currentOperation.innerText)
    const currentNumber = parseInt(value);

    currentOperation.innerText = `${previousNumber   currentNumber}`;
} 
  • Related