Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last value added to a text area using jQuery

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.

like image 215
Anthony_Z Avatar asked Dec 07 '25 07:12

Anthony_Z


2 Answers

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

like image 128
JRulle Avatar answered Dec 08 '25 21:12

JRulle


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" />
like image 22
Arun P Johny Avatar answered Dec 08 '25 21:12

Arun P Johny