skip to Main Content

I made a basic calculator. I’m trying to mimic google’s calculator when deleting an operator, it deletes the empty strings around the operator as well. This is the delete button I have.

deletebtn.addEventListener('click', () => {
currentDisplay.textContent = currentDisplay.textContent.slice(0, -1);
})

I’ve tried ‘if’ statements with split(), replace(), substring() to no avail.

2

Answers


  1. You should beware of the display element you use. If currentDisplay is <input> element then you can use currentDisplay.value to get and set the value.

    let currentDisplay = document.querySelector('#display');
    let deleteBtn = document.querySelector('#delete');
    let deleteAllBtn = document.querySelector('#deleteAll');
    
    deleteBtn.addEventListener('click', () => {
      //currentDisplay.textContent = currentDisplay.textContent.slice(0, -1);
      currentDisplay.value = currentDisplay.value.slice(0, -1);
    });
    
    deleteAllBtn.addEventListener('click', () => {
      //currentDisplay.textContent = currentDisplay.textContent.slice(0, -1);
      currentDisplay.value = '';
    });
    <input id="display" type="text" value="5+3" />
    <button id="delete">C</button>
    <button id="deleteAll">CE</button>

    If currentDisplay is not <input> element then you can use currentDisplay.textContent to get and set the value.

    let currentDisplay = document.querySelector('#display');
    let deleteBtn = document.querySelector('#delete');
    let deleteAllBtn = document.querySelector('#deleteAll');
    
    deleteBtn.addEventListener('click', () => {
      currentDisplay.textContent = currentDisplay.textContent.slice(0, -1);
      //currentDisplay.value = currentDisplay.value.slice(0, -1);
    });
    
    deleteAllBtn.addEventListener('click', () => {
      currentDisplay.textContent = '';
      //currentDisplay.value = currentDisplay.value.slice(0, -1);
    });
    <span id="display">5+3</span>
    <button id="delete">C</button>
    <button id="deleteAll">CE</button>
    Login or Signup to reply.
  2. CE stands for Clear Entry. In your case, based on your code, I think this should suffice:

    deletebtn.addEventListener('click', () => {
        currentDisplay.textContent = "";
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search