开发者

Catch pasted input in textarea

with javascript(Jquery).

Searched online, seems like it's not possible. So fa开发者_如何学Cr I have something like:

$("#textAreaId").bind('paste', function (e) {
        alert('pasting text!!!!');

        var data = $("#taData").val();

        alert(data);



    });

but the data is empty at this stage...is there a way to capture the pasted input after it's been pasted? Seems like there should be a way.

keyup event in Jquery is not triggered when pasting occurs.

Any ideas?


Here is what I have decided to do. Please note that I am merely required to grab the pasted content.

$(document).ready(function () {         

    $("#taData").bind('paste', function (e) {
        setTimeout(function () { DisplayPastedData(); }, 100);
    });    

});



function DisplayPastedData() {

    var data = $("#taData").val();
    alert('input pasted ' + data);


}

I have arbitrarily selected 100 milliseconds to wait, which works nicely with my maximum of data pasted.


Not all browsers support the same copy / paste capabilities. Here is a chart of which browser support which functions:

http://www.quirksmode.org/dom/events/cutcopypaste.html

If the browser supports capturing the copy / paste events, jQuery should work fine. I would suggest testing each of your targeted browsers.

Another approach would be to use the jQuery 'data' property to detect that the input field has changed. Here is an article with example code:

http://www.mydogboris.com/2009/10/using-jquery-data-feature-to-detect-form-changes/

from the article:

var formChanged = false;

$(document).ready(function() {
     $('#my_form input[type=text].editable, #my_form textarea.editable').each(function (i) {
          $(this).data('initial_value', $(this).val());
     });

     $('#my_form input[type=text].editable, #my_form textarea.editable').keyup(function() {
          if ($(this).val() != $(this).data('initial_value')) {
               handleFormChanged();
          }
     });

     $('#my_form .editable').bind('change paste', function() {
          handleFormChanged();
     });

     $('.navigation_link').bind("click", function () {
          return confirmNavigation();
     });
});

function handleFormChanged() {
     $('#save_or_update').attr("disabled", false);
     formChanged = true;
}

function confirmNavigation() {
     if (formChanged) {
          return confirm('Are you sure? Your changes will be lost!');
     } else {
          return true;
     }
}


Quite an old thread, but you might now use FilteredPaste.js (http://willemmulder.github.com/FilteredPaste.js/) instead. It will let you control what content gets pasted into a textarea or contenteditable and you will be able to filter/change/extract content at will.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜