最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the value of a field during the paste event? - Stack Overflow

programmeradmin0浏览0评论

I have a text field that I'm binding the paste event to using JQuery. When I first paste something into the form field and log its val() it returns a blank string. Likewise, if I paste again into the field, it returns the previous value before pasting. Essentially I have a race condition or sequencing issue, for lack of a better term. It seems the form field will not update until the paste event completes.

Is there any way to check the value of the field after the paste event has completed and the field is actually populated? I want the actual field value, not the clipboardData, as I know that's an IE-only feature.

$('#url').bind('paste', function(e) {
    alert($(this).val());
});

I have a text field that I'm binding the paste event to using JQuery. When I first paste something into the form field and log its val() it returns a blank string. Likewise, if I paste again into the field, it returns the previous value before pasting. Essentially I have a race condition or sequencing issue, for lack of a better term. It seems the form field will not update until the paste event completes.

Is there any way to check the value of the field after the paste event has completed and the field is actually populated? I want the actual field value, not the clipboardData, as I know that's an IE-only feature.

$('#url').bind('paste', function(e) {
    alert($(this).val());
});
Share Improve this question edited Jan 13, 2010 at 8:36 Justin Johnson 31.3k7 gold badges66 silver badges89 bronze badges asked Jan 13, 2010 at 7:59 SoviutSoviut 91.6k53 gold badges206 silver badges280 bronze badges 3
  • can't you use change event instead of paste? – kender Commented Jan 13, 2010 at 8:31
  • @kender - Only if the OP wants to wait until the user moves the focus away from the input. – Tim Down Commented Jan 13, 2010 at 9:37
  • 2 One important point: the paste event has existed in IE since version 5 but has only relatively recently made it into other browsers. Firefox 2, for example, doesn't have it. – Tim Down Commented Jan 13, 2010 at 9:39
Add a comment  | 

1 Answer 1

Reset to default 20

It turns out a decent solution is to wrap the callback in a setTimeout(), with a delay of 0 milliseconds, in order to make it asynchronous.

My new code is:

var urlField = $('#url');
urlField.bind('paste', function(e) {
    setTimeout(function() {
        alert(urlField.val());
    }, 0); // note the 0 milliseconds
});

Thanks to DigitalBush's Masked Input Plugin, it uses this technique throughout the source.

发布评论

评论列表(0)

  1. 暂无评论