Search code examples
jqueryajaxpreventdefaultquick-searchonpaste

setTimeout and e.preventDefault


I have two events listening on a unique field: autocomplete and onPaste. My goal is to call another logic on paste, and use the autocomplete on typing.

I did this in the following way:

$("#refno").on('paste', function (e) { 
    setTimeout(function () {
        //some logic here
    }, 0);
    e.preventDefault();
})

function quickSearch(fieldName) {
    //some other logic here
} 

quickSearch('.open-invoices-quick-search');

The problem is that the e.preventDefault(); is called or too early (preventing the code from the setTimeout), or too late, allowing the quickSearch function to be executed.

Any idea how to deal with this situation?

Here is the JSFddle: https://jsfiddle.net/mk242zkz/1/

Not possible to test as I can't find the autocomplete library.


Solution

  • You could use this logic instead, but style vague imho what is your expected behaviour...

    $("#refno").on('paste', function () {
        $(this).autocomplete("disable").one('keydown', function () {
            $(this).autocomplete("enable");
        });    
    });
    

    -jsFiddle-