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.
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.
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));
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">← </button>
<button id="excluir2">← </button>
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);
});
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">← </button>
Pattern
: .$
- search the last character Replace
:
- replaces "nothing".