John
John

Reputation: 13699

Is there a way to capture the changes to a textarea?

Here is what I am working with right now

$("#text").on("input", function(event){

    console.log("The changes are:" + SomeDataThatIDontKnowHowToAccess);

});

I realize that this could potentially break for the backspace/pasting over text/insert/delete. I don't really know how this could be handled, maybe have delete/insert/override events... I'd rather not roll my own solution.

An Example

The user pastes something in a blank textarea

{eventType:'insert', value:'something'}

shows up in the console

Upvotes: 2

Views: 732

Answers (4)

Adriano Carneiro
Adriano Carneiro

Reputation: 58595

Two things you have to do here. First, you have to cache the last value. This way,when the new value comes in, you have what to compare it with.

Second, you need to take a look (and download) a string diff function made available by John Resig. You'd get the output of the diff into a div's html. The result looks awesome.

Then, your solution would look like this:

$("#text").data('lastvalue', $("#text").val());
$("#text").on("input", function(event){
    var diff = diffString($("#text").data('lastvalue'), $("#text").val()); 
    $('#changesdiv').html("The changes are:" + diff);
    $("#text").data('lastvalue', $("#text").val());
});​

Update

I fixed a few errors on script and got a jsfiddle running at http://jsfiddle.net/m3KAa/6/

IMHO, this diffString function is really awesome.

Upvotes: 1

BLSully
BLSully

Reputation: 5929

Write the old value to some place you can persist on focus. Then you can use your own logic in the change event to find the differences between old and new values

$('#text').on('focus', function () {
    //THIS LINE IS INCORRECT [what was wrong with my fiddle]... assignment is parameter *doh*
    //$(this).data('oldValue') = $(this).val();
    //THIS IS THE CORRECT LINE
    $(this).data('oldValue', $(this).val());
}).on('change', function() {
    alert('Old Value: ' + $(this).data('oldValue') + '\nNew Value: ' + $(this).val());
});

Fiddle for ya: http://jsfiddle.net/BLSully/jqbAr/1/ [fixed]

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

Try this

// This event can be used when the textarea loses focus

$("#text").on("change", function(event){

    console.log("The changes are:" + $(this).val() );

});

// This event can be used user starts typing and key is presed

 $("#text").on("keyup", function(event){

        console.log("The changes are:" + $(this).val() );

    });

//

$("#text").on("input",   // Here input is not a event you are supposed to used

// Try using change event instead..

Upvotes: 0

Anton Baksheiev
Anton Baksheiev

Reputation: 2251

if you need get current value you need to use keyup event

$("#text").on("keyup ", function(event){
    console.log("The changes are:" + $(this).val() );
});

Upvotes: 0

Related Questions