简体   繁体   中英

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.

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-

JqueryUI autocomplete provides some stock methods that you can call on the autocomplete element during and after initialization.

I'm sure you've seen it already but check out the API docs here for autocomplete: Autocomplete Docs

Inside of your paste event try using the disable method on your autocomplete object. Don't forget to re-enable it after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM