jQuery delete the last entered character in an input

0

I would like to know how to delete only the last letter entered in an input field.

All the examples I've found are cleaning the whole field.

    
asked by anonymous 27.07.2017 / 18:27

4 answers

2

takes the value of the input, removes the last character and updates the input.

var texto = $("#input_id").val();
$("#input_id").val(texto.substring(0, texto.length - 1));
    
27.07.2017 / 18:33
4

You can use slice() or substring() to create a new string from the first character to the penultimate character and then make this new string new value of input .

About methods :

slice() draws a piece of one string and returns a new one. The first parameter is the initial position of the "extraction" and the second parameter is the final position. Using -1 is equivalent to the last position, and so on. See more in the documentation .

The substring works similarly, with few differences, one is that it is not possible to use negative indexes. See more in the documentation .

Example :

$('#excluir').on('click', function (){
  var input = $('#txt');
  input.val(input.val().slice(0, -1));
});

$('#excluir2').on('click', function (){
  var input = $('#txt');
  var texto = input.val();
  input.val(texto.substring(0, texto.length - 1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="txt" type="text" value="Isso é um teste!" />
<button id="excluir">← &nbsp;&nbsp;&nbsp;</button>
<button id="excluir2">← &nbsp;&nbsp;&nbsp;</button>
    
27.07.2017 / 18:32
1

Clicking the button will capture the input value and remove the last character. After that you will set the new value for the input.

 $("#idBotao").click(function(){
        var input_novo_valor = $("#idInput").text().slice(0,-1); 
        $("#idInput").val(input_novo_valor);
    });
    
27.07.2017 / 18:38
0

I like REGEX so I'll provide an answer with the same, although @ jbueno already solves perfectly the question.

$('#excluir').on('click', function (){
  var input = $('#txt')[0];
  input.value = input.value.replace(/.$/, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="txt" type="text" value="Isso é um teste!" />
<button id="excluir">← &nbsp;&nbsp;&nbsp;</button>

Explanation

  • Pattern : .$ - search the last character
  • Replace : - replaces "nothing".
27.07.2017 / 20:17