I am adding letters and words to an empty text area using the following code:
HTML:
<textarea id="Content"></textarea>
<button class="AddTo" value="a">a</button>
jQuery:
$('.AddTo').on('click', function() {
$('#Content').append($(this).val());
});
How can I delete the last value added to the text area such as "a" or "apple" without clearing everything? Basically I want a delete button to remove the last character.
You should keep an array of the values added to the textarea in javascript. If you want to revert back 1 word (or more) you would simple pop off the values from the array then populate the textarea from the shortened array.
Example:
var values = [];
$(function(){
$('.AddTo').on('click', function() {
values.push($(this).val());
$('#Content').val( values.join(" ") );
});
$('.Backspace').on('click', function(){
values.pop();
$('#Content').val( values.join(" ") );
});
});
JSFiddle DEMO
Demo with freeform text field: jsfiddle
You need to keep track of the values inserted, you can use an array to do that as given below, then use that to remove the content
var values = [];
$('.AddTo').on('click', function() {
values.push($(this).val());
$('#Content').val($('#Content').val() + values[values.length - 1]);
});
$('.remove').click(function() {
if (values.length) {
$('#Content').val(function(i, v) {
return v.slice(0, -values.pop().length)
});
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="Content"></textarea>
<br />
<button class="remove">Remove</button>
<input type="button" class="AddTo" value="a" />
<input type="button" class="AddTo" value="apple" />
<input type="button" class="AddTo" value="some" />
<input type="button" class="AddTo" value="value" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With