Reputation: 21
I’m trying to create a button that when pressed will remove the last character entered in a text field called “screen” using jQuery. This is the code I already have created but it does not work. Help would be appreciated :)
var currentEntry = $("#screen").text();
$("#back").click(function(){
currentEntry = currentEntry.substring(0, currentEntry.length-1);
});
Upvotes: 2
Views: 366
Reputation: 1092
You can use slice(), substr() or substring() method to chop the last character from string.
Try the code below using substr() method:
$("#back").click(function() {
var currentEntry = $("#screen").val();
$("#screen").val(currentEntry.substr(0, currentEntry.length-1));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<input id="screen" type="text" value="screen">
<button id="back" type="button">Click Me!</button>
If you are familiar with slice() method, you can use it like this way:
$("#screen").val(currentEntry.slice(0, -1));
Upvotes: 2
Reputation: 115222
You need to update the text in DOM, so use text()
method with a function which helps to update using returned value.
$("#back").click(function(){
$("#screen").text((i, text) => text.slice(0,-1));
});
$("#back").click(function() {
$("#screen").text((i, text) => text.slice(0, -1));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="screen">jshdjhsdhjshjhdsjdhsjdhsjhjshds</div>
<button id="back">back</button>
If it's a textarea then you have to use val()
method in same way to update the value.
$("#back").click(function(){
$("#screen").val((i, text) => text.slice(0,-1));
});
$("#back").click(function() {
$("#screen").val((i, text) => text.slice(0, -1));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="screen">jshdjhsdhjshjhdsjdhsjdhsjhjshds</textarea>
<button id="back">back</button>
Upvotes: 1