How to get the value of a field during the paste event?

浪子不回头ぞ 提交于 2019-12-20 20:31:09

问题


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());
});

回答1:


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.



来源:https://stackoverflow.com/questions/2055224/how-to-get-the-value-of-a-field-during-the-paste-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!