Delete last entered digit

Asked

Viewed 676 times

-2

I’m creating a calculator, using HTML and Javascript. My goal was that it had itself a button that allows the user to delete the last entered value (for example, the user enters the number 9 and then 8 and form 98, but he wants to erase the 8, then he pushes that button to make the value go back to being just 9), but I’m not being able to create a function for that.

I would like a code, in Javascript, to solve this problem.

Imagem da minha calculadora.

2 answers

1

Use the method substring, input.value = inputText.substring(0,inputText.length-1);

<input id="input" type="text"/>
<button onclick="apagar()">Apagar</button>

<script>
function apagar() {
  let input = document.getElementById('input');
  let inputText = input.value;
  input.value = inputText.substring(0,inputText.length-1);
  console.log(input.value);
}</script>

  • 1

    Or (if the entry is a valid number) Math.floor(inputText/10).

  • It is... if you have with mask, formatting etc... But he said nothing.

  • Man, I work the way I wanted, thank you very much =)

  • Mark the answer as a solution then. The user who helped you deserves to take credit

1

You can use the function slice:

var str=document.getElementById("campo-com-o-valor").value;
str = str.slice(0, -1);
  • Sorry about the format, I answer by cell phone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.